1

我正在尝试使用选择器以便用户能够选择小时。我用相应的 android XML 创建了一个 FragmentActivity。FragmentActivity 如下:

public class MainActivity extends FragmentActivity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TimePickerFragment tpf = new TimePickerFragment();
    tpf.getFragmentManager();

}


public static class TimePickerFragment  extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
 final Calendar c = Calendar.getInstance();
 int hour = c.get(Calendar.HOUR_OF_DAY);
 int minute = c.get(Calendar.MINUTE);

 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 
 }

 public void showTimePickerDialog(View v) {
   DialogFragment newFragment = new TimePickerFragment ();
   newFragment.show(getFragmentManager(), "timePicker");
 }

}
}

XML 如下:

 <RelativeLayout 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" >

  <Button 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content"
   android:text="@string/hello_world" 
   android:onClick="TimePickerFragment " />

</RelativeLayout>

代码检索自:http: //developer.android.com/guide/topics/ui/controls/pickers.html

现在,问题是我无法看到带有日期的选择器。它只是显示一个白屏。我究竟做错了什么?

PS 我所做的唯一更改是我使用 getFragmentManager() 而不是 getSupportFragmentManager()。这就是为什么,当我使用最后一个时遇到错误。

4

2 回答 2

2

FragmentActivity是支持库的一部分,所以当你扩展它时,你必须使用getSupportFragmentManager(). 如果您在执行此操作时遇到错误,请发布错误。

于 2012-10-27T20:36:33.240 回答
2

你的android:onClick属性不正确。你的 xml 应该是:

<RelativeLayout 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" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showTimePickerDialog"
        android:text="Pick Time" />

</RelativeLayout>

showTimePickerDialog现在将在用户单击Button. 这个方法应该在MainActivity.

此外,您需要通过调用来设置要使用的布局setContentViewMainActivity看起来像这样(我没有包括在内TimePickerFragment):

public class MainActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }
    public static class TimePickerFragment extends android.support.v4.app.DialogFragment implements
        TimePickerDialog.OnTimeSetListener {
        ...
    }

}
于 2012-10-27T20:36:38.400 回答