Dev/Android

2. 안드로이드 프래그먼트에서 버튼으로DatePickerDialog 사용

zapi 2023. 8. 17. 22:38

액티비티에서 작동하는 것은 많지만 프래그먼트는 자료가 많이 없어서 내가 직접 정리하려고 한다.
// 프래그먼트 자료도 액티비티 만큼 많이 생겼음 하는 바램에서 내가 먼저 실천해야지! 히힣

프래그먼트에서 버튼을 이용해서 날짜를 정하고 DatePickerDialog로 픽된 날짜를 해당
프래그먼트 화면에 출력
먼저 DatePickerDialog.java이다.

 

DatePickerDialog.java

public class DatePickerDialog extends Fragment {
    
    public int pYear, pMonth, pDay;
    String pickedDate;

    Button pickDate;
    TextView selectedDate;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();

        pickDate = (Button) getView().findViewById(R.id.date);
        selectedDate = (TextView) getView().findViewById(R.id.selectedDate);

        // 달력 갖고오기

        GregorianCalendar calendar = new GregorianCalendar();
        pYear = calendar.get(Calendar.YEAR);
        pMonth = calendar.get(Calendar.MONTH);
        pDay = calendar.get(Calendar.DAY_OF_MONTH);
        
        pickDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(getActivity(), mDateSetListner, sYear, sMonth, sDay).show();
                pickedDate = selectedDate.getText().toString();
            }
        });
    }
    DatePickerDialog.OnDateSetListener mDateSetListner =
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    pYear = year;
                    pMonth = month;
                    pDay = dayOfMonth;

                    selectedDate.setText(String.format("%d / %d / %d", pYear, pMonth +1, pDay));
                }
            };
}

 

fragement.xml

<TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableRow android:layout_weight="1">
            <Button
                android:id="@+id/date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="날짜 설정"/>
            <TextView
                android:id="@+id/selectedDate"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="12pt"
                android:layout_marginTop="3pt"
                android:layout_marginLeft="3pt"
                android:textColor="@android:color/holo_blue_dark"
                android:layout_weight="1"/>
</TableLayout>