2013-10-08 37 views
4

我從Android DevelopersTimepicker不是靜態的允許

了原來的TimePicker - 源代碼,並將其粘貼在Android Studio中的新類。 Android Studio引發錯誤「禁止在此處允許使用」靜態「修飾符」。怎麼了?這裏的來源:

public static class TimePickerFragment extends DialogFragment 
         implements TimePickerDialog.OnTimeSetListener { 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     // Use the current time as the default values for the picker 
     final Calendar c = Calendar.getInstance(); 
     int hour = c.get(Calendar.HOUR_OF_DAY); 
     int minute = c.get(Calendar.MINUTE); 

     // Create a new instance of TimePickerDialog and return it 
     return new TimePickerDialog(getActivity(), this, hour, minute, 
       DateFormat.is24HourFormat(getActivity())); 
    } 

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
     // Do something with the time chosen by the user 
    } 
} 

而且順便說一句:有一種簡單的方法來在活動中使用timepicker?這裏幾乎所有的例子都是用「showDialog()」來處理的,它被depricated。

+1

Java基礎...谷歌爲:我們何時應該使用靜態Java類 – Selvin

回答

7

提供的示例隱含地假設您將該代碼作爲內部類添加到另一個ActivityFragment中。如果這不是你正在做的,請從中刪除static。請注意,DialogFragment在外部類中的通信會讓人感到厭煩(您將不得不使用接口來回通信)。

關於你提到的第二個問題,以顯示對話框使用類似:

DialogFragment dialog = new MyDialogFragment(); 
dialog.show(getFragmentManager(), "MyDialog"); 
0

首先,感謝Kasra!

我也發現,你必須把它放在一個對話框片段。但是這些都是從API 11開始的(我的API將支持從API 5開始)。 可以通過在Android Studio中安裝兼容包來使用它們。所以我等待deprication,也許在API 20我的應用程序已經過時了:-)

1

你試圖粘貼上面的內容並行到活動類減速,實際上上面的代碼應該是一個內部類。

public class NewCaseEntry extends AppCompatActivity {} 
public static class TimePickerFragment extends ... {} 

這是不對的,應該是

public class NewCaseEntry extends AppCompatActivity { 
    public static class TimePickerFragment extends ... {} 
}