在Android上显示选择器

时间:2012-10-27 20:16:34

标签: android

我试图使用拣货员,以便用户能够选择小时。我用相应的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

中检索的

现在,问题是我无法看到带有日期的拣货员。它只显示一个白色的屏幕。我做错了什么?

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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时,系统会调用{p> Button。此方法应位于MainActivity

此外,您需要通过调用setContentView来设置要使用的布局。 MainActivity看起来像这样(我没有包含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 {
        ...
    }

}