2016-11-29 150 views
0

我按照這裏的說明:https://developer.android.com/guide/topics/ui/controls/pickers.html如何在Android Studio中正確創建日期選擇器?

我向下滾動到「創建日期選擇器」,並複製粘貼在一個文件中的代碼名爲DatePickerFragment.java

public static class DatePickerFragment extends DialogFragment 
          implements DatePickerDialog.OnDateSetListener { 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     // Use the current date as the default date in the picker 
     final Calendar c = Calendar.getInstance(); 
     int year = c.get(Calendar.YEAR); 
     int month = c.get(Calendar.MONTH); 
     int day = c.get(Calendar.DAY_OF_MONTH); 

     // Create a new instance of DatePickerDialog and return it 
     return new DatePickerDialog(getActivity(), this, year, month, day); 
    } 

    public void onDateSet(DatePicker view, int year, int month, int day) { 
     // Do something with the date chosen by the user 
    } 
} 

然後我在activity_front_page.xml創造了這個按鈕:

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/pick_date" 
    android:onClick="showDatePickerDialog" /> 

並加入此代碼到DatePickerFramegent類:

public void showDatePickerDialog(View v) { 
    DialogFragment newFragment = new DatePickerFragment(); 
    newFragment.show(getSupportFragmentManager(), "datePicker"); 
} 

但是這是說getSupportFrammentManager()沒有定義?

我是使用Android工作室和開發Andriod的新手。我想要的是日期選擇器(如果您訪問上面提供的鏈接,它的圖片會顯示在屏幕的頂部附近)。任何想法如何解決這個問題?

+1

你嘗試Android的自身datepickerdialog https://developer.android.com/reference/android/app/DatePickerDialog.html –

+0

您是否在活動中擴展Activity類或AppCompatActivity類? –

回答

0

當你使用android.support.v4.app.DialogFragment,你應該通過展示()android.support.v4.app.FragmentManager的一個實例可以使用getSupportFragmentManager查詢()調用

0

嘗試下面的代碼,看看是否有幫助:

Activity activity = getActivity; 
DatePickerDialog datePickerDialog = new DatePickerDialog(activity, AlertDialog.THEME_HOLO_LIGHT, 
       new DatePickerDialog.OnDateSetListener() { 

        @Override 
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 

       }, year, mm, dd); 
     datePickerDialog.show(); 
0

你需要FragmentTransactiongetSupportFragmentManager()

public void showDatePickerDialog(View v) { 
FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 

DialogFragment newFragment = new DatePickerFragment(); 
newFragment.show(ft, "datePicker"); 
} 
相關問題