2015/10/13

Android 自訂AlertDialog

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

LinearLayout linearLayout = new LinearLayout(EngineerActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(params);

TextView textView = new TextView(EngineerActivity.this);
textView.setText("請輸入文字:");

EditText editText = new EditText(EngineerActivity.this);
editText.setInputType(InputType.TYPE_CLASS_TEXT);

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

Button buttonCancel = new Button(EngineerActivity.this);
buttonCancel.setText("取消");
buttonCancel.setOnClickListener(new OnClickListener() {

 @Override
 public void onClick(View v) {
  Toast.makeText(getApplicationContext(), "取消", 1).show();
  dialog.cancel();
 }
});

// 新增至LinearLayout
linearLayout.addView(textView);
linearLayout.addView(editText);
linearLayout.addView(buttonAdd);
linearLayout.addView(buttonCancel);

// 設定View
dialog.setView(linearLayout);

// 顯示
dialog.show();

執行結果: