我为打开的自定义对话框名称 dlg_option 创建OptionActivity和菜单。在对话框dlg_option中,我有用于打开日历的TextView ID txt_time 。
这是选项活动
public class OptionActivity extends AppCompatActivity {
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m_option);
/************** This is open claenda code ************/
mDisplayDate = (TextView) findViewById(R.id.txt_time);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(OptionActivity.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = dayOfMonth + "/" + month + "/" + year;
mDisplayDate.setText(date);
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/************ This is menu ****************/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
switch (item.getItemId()){
case R.id.m_menu1:
builder.setView(inflater.inflate(R.layout.dlg_option, null));
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(OptionActivity.this, "menu ok",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(OptionActivity.this, "menu cancel",
Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
}).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
它显示错误 java.lang.NullPointerException
当我单击m_menu1时,必须显示dlg_option,而当我在dlg_option中单击txt_time时,必须显示calenda作为选择日期。该如何解决?
答案 0 :(得分:0)
如果您的txt_time
视图在对话框中,而不是在活动的常规布局中,那么您将无法通过在活动的onCreate()方法中调用findViewById()
来找到它。相反,您应该在创建对话框时找到它。
在设置对话框视图时:
builder.setView(inflater.inflate(R.layout.dlg_option, null));
您需要将inflate()
提取到局部变量,然后在此处使用findViewById()
。
View dialogBody = inflater.inflate(R.layout.dlg_option, null);
mDisplayDate = (TextView) dialogBody.findViewById(R.id.txt_time);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
...
});
builder.setView(dialogBody);