テキスト入力つきのダイアログ作成
コメント欄とかをつけたダイアログ作成に使う
TwitterとかFacebookなどの投稿にも使えるし、メールアプリなどに使うのもわかりやすくなる
テキスト入力つきダイアログ作成するには
EditTextを表示できるレイアウトを作成し
setView()でAlertDialogのコンテンツとして割り当てる
まずは、レイアウトファイルを作成し
テキスト入力用のレイアウトを作成
<LinearLayout xmlns:android="http://scheams.android.com/apk/res/android" android:id="@+id/layout_root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tweet !"/> <EditText android:id="@+id/text" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
次に、JavaでAlertDialog.Builderの設定
//カスタムビューの設定
LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View layout = (LinearLayout)findViewById(R.id.layout_root);
//AlertDialog生成
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//タイトル設定
builder.setTitle("Tweet Dialog");
//レイアウト設定
builder.setView(layout);
//OKボタン設定
builder.setPositiveButton("ok",new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
EditText tweet = (EditText)findViewById(R.id.text);
String string = tweet.getText().toString();
}
});
//Cancelボタン設定
builder.setNegativeButton("cancel",new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
//キャンセルなので何もしない
}
});
//ダイアログの表示
builder.create().show();
ダイアログの作り方は
作成したレイアウトを
LayoutInflater.inflate()で読み込んで
AlertDialog.setView()
でAlertDialogのコンテンツに割り当てている