2013-02-26 60 views
5

我一直在試圖創建一個對話框一個時間選擇器,我得到的片段類說法的錯誤:安卓:時間選擇對話框

的方法is24HourFormat(活動)是不確定的 型日期格式在下面的行中。

在行

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> 

回答

13

您導入了java.text.DateFormat,您需要導入android.text.format.DateFormat。你正在使用錯誤的類。

3

發生這種情況的原因是因爲您使用了錯誤的DateFormat。

您有:

import java.text.DateFormat; 

當你想:

import android.text.format.DateFormat 

總之,這兩個對象具有相同的名稱,但它們不是同一個對象。所以你必須專門使用android提供的,因爲它是唯一知道如何處理Context的方法,你調用的方法是DateFormat.is24HourFormat(getActivity()));