2015/10/13

Android 自訂AlertDialog 2

不喜歡看到很雜的程式碼,也可以在layout先設計好畫面
而透過LayoutInflater來帶入,不過要注意的dialog調用的方法為setView,而不是setContentView
要加入監聽事件則必須透過view來findViewById,而不是透過context的findViewById來找尋

Code:
AlertDialog.Builder builder = new AlertDialog.Builder(EngineerActivity.this);
final AlertDialog dialog = builder.create();

LayoutInflater inflater = LayoutInflater.from(EngineerActivity.this);
View view = inflater.inflate(R.layout.test, null);
//上面兩行也可以縮減為
//View view = View.inflate(EngineerActivity.this, R.layout.test, null);


Button buttonAdd = (Button) view.findViewById(R.id.button1);
buttonAdd.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
   Toast.makeText(getApplicationContext(), "新增成功", 1).show();
   dialog.cancel();
 }
});

Button buttonCancel = (Button) view.findViewById(R.id.button2);
buttonCancel.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
  Toast.makeText(getApplicationContext(), "取消", 1).show();
  dialog.cancel();
 }
});

dialog.setView(view);
dialog.show();


XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="請輸入文字:" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:text="新增" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:text="取消" />

</RelativeLayout>

執行結果:
同Android 自訂AlertDialog