0

我正在尝试在时间选择器对话框中放置一个复选框,位于时间选择器上方,只要它被选中,时间选择器就可以工作。
我尝试在 TimePickerFragment(onCreateDialog) 中制作 CheckBox,并将复选框放在主活动中,而不是在时间对话框中。TimePickerFragment:

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    private MyAlarmReceiver alarm;
    //final CheckBox chk=null;
    @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);

        final CheckBox chk = (CheckBox) getActivity().findViewById(R.id.chk);
        if (chk.isChecked()) {
            chk.setChecked(false);
        }
        // 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) {
        Context con = getActivity();
        MainActivity.hour = hourOfDay;
        MainActivity.min = minute;
        //Toast.makeText(con, "TimeGet: "+MainActivity.hour+","+MainActivity.min, Toast.LENGTH_LONG).show();
        alarm = new MyAlarmReceiver();
        if(alarm != null){alarm.setOnetimeTimer(con);}
        else
            Toast.makeText(con, "Alarm is null", Toast.LENGTH_SHORT).show();
    }
}

Main_activity.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"
    android:id="@+id/layout"
    android:background="@drawable/back" >
    <CheckBox
        android:id="@+id/chk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk" 
        android:checked="true"/>
    </RelativeLayout>

知道为什么吗?谢谢!

4

2 回答 2

2

Fragments没有findViewById()方法,因此出现错误。

由于您似乎想获得对 Activity 复选框的引用,因此获取 Activity 实例然后调用findViewById()应该会给出所需的结果:

final CheckBox chk = (CheckBox) getActivity().findViewById(R.id.chk);
if (chk.isChecked()) {
     chk.setChecked(false);
}

正如 ChriZzZ 所提到的,无法访问的代码是您应该遇到的另一个编译器错误。

于 2013-05-11T19:42:52.200 回答
0

我很确定您会收到一条警告/错误消息:无法访问代码。

您在到达 findViewById 之前返回并因此离开该方法。

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

final CheckBox chk = (CheckBox) findViewById(R.id.chk);
于 2013-05-11T19:38:44.740 回答