我想創建一個DatePicker對話框,當我按照自定義佈局創建的對話框中的按鈕時打開。我已經嘗試了許多不同的代碼配置,並且按下按鈕時的結果始終是NullPointerException或按鈕不執行任何操作。我對android編程非常陌生,但我最好的猜測是findViewById無法找到按鈕,因爲我正在使用Fragment並且未指定內容視圖。我試圖使用setContentView,但那不起作用。希望有人可以弄清楚,讓我知道他們是怎麼做到的!NullPointerException當在片段中設置onClickListener
NewTaskDialogFragment.java:
public class NewTaskDialogFragment extends DialogFragment implements
android.view.View.OnClickListener {
public int mYear, mMonth, mDay;
public static final int DIALOG_ID = 0;
private Button btn;
private View dialogView;
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
dialogView= inflater.inflate(R.layout.new_task_dialog, null);
builder.setView(dialogView)
;
btn =(Button) dialogView.findViewById(R.id.datePickerDialogButton);
showDialogOnButtonClick();
return builder.create();
}
public void showDialogOnButtonClick(){
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().showDialog(DIALOG_ID);
}
});
}
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
TextView dateDisplay = (TextView) getActivity().findViewById(R.id.dateDisplayBox);
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateDisplay.setText(mYear + mMonth + mDay);
}
};
@Override
protected Dialog onCreateDialog(int id){
if(id == DIALOG_ID) {
return new DatePickerDialog(getActivity(), dpickerListener , mYear, mMonth, mDay);
}else{
return null;
}
}
@Override
public void onClick(View view) {
}
}
你的'getActivity()'返回** null **嗎? –