[英]Android: Time Picker Dialog
我一直試圖在對話框中創建一個時間選擇器,我在片段類中得到一個錯誤:
對於以下行中的DateFormat類型,方法is24HourFormat(Activity)未定義。
在線
DateFormat.is24HourFormat(getActivity()));
這是Android開發者網站上的一個例子,所以我沒想到會有任何錯誤。 我已經顯示了下面的代碼。
如果有人可以幫助我,我將非常感激。
謝謝
碼
package com.app.timer2;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import com.app.timer.R;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
}
分段
package com.app.timer2;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.TimePicker;
public 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
}
}
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical" >
<Button
android:id="@+id/start_time_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:padding="10dp"
android:text="@string/start_time_button"
android:onClick="showTimePickerDialog" />
</LinearLayout>
你導入了java.text.DateFormat
,你需要導入android.text.format.DateFormat
而不是......你使用的是錯誤的類。
發生這種情況的原因是因為你使用了錯誤的DateFormat。
你有:
import java.text.DateFormat;
當你想要的時候:
import android.text.format.DateFormat
總之,這兩個對象具有相同的名稱,但它們不是同一個對象。 所以你必須專門使用android提供的一個,因為它是唯一一個知道如何處理Context
的方法,你正在調用DateFormat.is24HourFormat(getActivity()));
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.