我有一个自定义对话框,上面有datepicker
。在我的Fragment
我有一个按钮,当我按下它时,对话框出现,我从datepicker
中选择日期。我希望所选日期显示在textview
的{{1}}上。我的代码如下:
这是我的主Fragment
上包含Activity
的对话框的代码:
Fragment
我从public int day;
public int month;
public int year;
@SuppressLint("InflateParams")
@SuppressWarnings("deprecation")
public void SetDate(){
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Select Date");
alertDialog.setIcon(R.drawable.action_reservations);
LayoutInflater layoutInflater = LayoutInflater.from(context);
View promptView = layoutInflater.inflate(R.layout.datepicker, null);
alertDialog.setView(promptView);
final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
final TextView PickedDate = (TextView) findViewById(R.id.pickeddate);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
day=datePicker.getDayOfMonth();
month=datePicker.getMonth() + 1;
year=datePicker.getYear();
PickedDate.setText(new StringBuilder().append(day).append(" ").
append("-").append(month).append("-").append(year));
}
});
// Showing Alert Message
alertDialog.show();
}
获取日期,月份和年份,并使用
datepicker
同样在我的片段中,我使用下面的代码调用我的对话框:
PickedDate.setText(new StringBuilder().append(day).append(" ").
append("-").append(month).append("-").append(year));
当我运行我的应用程序时,我在这些行上得到了一个nullPointerException:
final Button SetDate = (Button)rootView.findViewById(R.id.selectdate);
SetDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((MainActivity) getActivity()).SetDate();
}
});
我做错了什么?提前致谢
答案 0 :(得分:0)
尝试替换
final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
final TextView PickedDate = (TextView) findViewById(R.id.pickeddate);
有了这个
final DatePicker datePicker = (DatePicker) promptView.findViewById(R.id.datePicker1);
final TextView PickedDate = (TextView) promptView.findViewById(R.id.pickeddate);