2

我有一个需要显示 TimePicker 对话框的应用程序。我可以让 TimePicker 在应用程序上显示,但是当我尝试附加侦听器时似乎抛出了 NPE。这是否正确实施?

LayoutInflater li = LayoutInflater.from(NfcscannerActivity.this);
View promptsView = li.inflate(R.layout.dialogboxmanuallogout, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(NfcscannerActivity.this);

// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);

//final EditText userInput = (EditText) promptsView
//.findViewById(R.id.editTextDialogUserInput);

final TimePicker tp = (TimePicker)findViewById(R.id.timepicker1);
tp.setOnTimeChangedListener(timeChangedListener);

// set dialog message
alertDialogBuilder
    .setCancelable(false)
    .setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {

                //Log.e(TAG, "about to get the hour from tp");
                //Integer hour = new Integer(1);
                //int hour = tp.getCurrentHour();
                //Log.e(TAG, "just got the hour from tp");
                //Integer minute = tp.getCurrentMinute();

                Toast.makeText(NfcscannerActivity.this,
                    "Last logout has been updated at "+ tp.getCurrentHour() + tp.getCurrentMinute() ,
                    Toast.LENGTH_LONG).show();

            }
        })
    .setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();



private TimePicker.OnTimeChangedListener timeChangedListener = new TimePicker.OnTimeChangedListener() {

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        // TODO Auto-generated method stub
        Log.e(TAG, "time changed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }
};

[更新1]

.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Please enter time of last logout"
        android:textAppearance="?android:attr/textAppearanceLarge" />





    <TimePicker
        android:id="@+id/timepicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />







</LinearLayout>
4

1 回答 1

1

您正在尝试从活动的内容视图而不是对话框中查找视图。

所以在alertDialogBuilder.create();使用下面的代码之后

final TimePicker tp = (TimePicker)promptsView.findViewById(R.id.timepicker1);
tp.setOnTimeChangedListener(timeChangedListener);
于 2012-09-14T09:55:46.773 回答