我有一个需要显示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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
};
[UPDATE1]
<?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>
答案 0 :(得分:1)
您正尝试从活动的内容视图而不是Dialog中查找视图。
所以alertDialogBuilder.create();
使用下面的代码
final TimePicker tp = (TimePicker)promptsView.findViewById(R.id.timepicker1);
tp.setOnTimeChangedListener(timeChangedListener);