2017-10-19 5 views
0

私は、ユーザーがAlertDialogに含まれているDatePickerから日付を選択したいというアクティビティを持っています。 AlertDialogでは、1つのDatePickerを持つLinearLayoutだけを含むxmlレイアウトファイルにビューを設定しました。Androidスタジオ - AlertDialogのDatePicker、ヌルオブジェクト参照

コードはとてもシンプルで、onCreate()のすぐ下にあります。

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
alert.setView(R.layout.activity_alertdialog_date); 
DatePicker datePicker = (DatePicker) findViewById(R.id.Activity_AlertDialog_SetStartDate); 
// ... The rest of the AlertDialog, with buttons and all that stuff 
alert.create().show() 

レイアウトがAlertDialogに表示され、その部分が素晴らしい作品。 しかし、私はこの行を追加しようとすると、私はnullオブジェクト参照エラーが発生します。ここで

datePicker.setMinDate(System.currentTimeMillis() - 1000); 

がエラーでありますメッセージ。

どのように私はこの問題を解決する、または別の方法で自分のコードを向上させることができますか?nullのオブジェクト参照の上

を仮想メソッド「空 android.widget.DatePicker.setMinDate(長い)」を呼び出すため

試み 私が得ることができるすべての助けに本当に感謝します。ありがとう!

+0

この行 'datePicker.setMinDate(System.currentTimeMillis() - 1000);)を使用しようとしていますか? 'datePicker'はスコープ内にありますか? – DigitalNinja

+0

次の行です。これは、私がonCreate()の最後に呼び出すメソッドにあります。そこで、setContentView(...)の直下のメソッドを呼び出しています。 – Fred

+1

Sidenote:AlertDialog.Builderの呼び出しを連鎖させることができます。つまり、 'AlertDialog.Builder(this).setView(R.layout.my_layout) .setButtonPositive(R.string.sweet_text).create()。show() 'を使用すると、コードを読みやすくすることができます。 – emerssso

答えて

1

あなたの問題は、findViewByIdがDatePickerビューの間違った場所にあることです。アクティビティ内でfindViewByIdを呼び出すと、ダイアログのレイアウトではなく、アクティビティのレイアウト階層で呼び出されます。まずアラートダイアログのレイアウトを膨張させてから、ビューへの参照を取得する必要があります。これは2つの方法で達成することができます。

おそらく最も簡単なビューを膨らませると、ダイアログを表示する前に参照を取得することです:

View dialogView = LayoutInflater.from(this).inflate(R.layout.activity_alertdialog_date, false); 
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.Activity_AlertDialog_SetStartDate); 

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
alert.setView(dialogView); 
// ... The rest of the AlertDialog, with buttons and all that stuff 
alert.create().show(); 

それが作成されていた後、あなたはまた、警告ダイアログからのビューを得ることができる:

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
alert.setView(R.id.Activity_AlertDialog_SetStartDate); 
// ... The rest of the AlertDialog, with buttons and all that stuff 
AlertDialog dialog = alert.create(); 

dialog.show(); 
DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.Activity_AlertDialog_SetStartDate); 
+0

完璧、ありがとう! – Fred

関連する問題