Android自定义AlertDialog

时间:2023-03-09 21:48:41
Android自定义AlertDialog

常见的一种方法:

[html] view plaincopyprint?Android自定义AlertDialogAndroid自定义AlertDialog

  1. AlertDialog.Builder builder;

  2. AlertDialog alertDialog;

  3. LayoutInflater inflater = getLayoutInflater();

  4. // 添加自定义的布局文件

  5. View layout = LayoutInflater.from(TestOne.this).inflate(

  6. R.layout.dialog, null);

  7. final TextView text = (TextView) layout.findViewById(R.id.tv1);

  8. // 添加点击事件

  9. text.setOnClickListener(new OnClickListener() {

  10. @Override

  11. public void onClick(View v) {

  12. // TODO Auto-generated method stub

  13. text.setText("call");

  14. }

  15. });

  16. builder = new AlertDialog.Builder(TestOne.this);

  17. alertDialog = builder.create();

  18. // 去掉边框的黑色,因为设置的与四周的间距为0

  19. alertDialog.setView(layout, 0, 0, 0, 0);

  20. alertDialog.show();

  21. // 修改大小

  22. WindowManager.LayoutParams params = alertDialog.getWindow()

  23. .getAttributes();

  24. params.width = 350;

  25. params.height = 200;

  26. alertDialog.getWindow().setAttributes(params);

这样 ,重新给它填充自定义的布局视图,但缺乏可扩展性,而且每次使用还得重新定义。

重写AlertDialog类,定义方法:

[html] view plaincopyprint?Android自定义AlertDialogAndroid自定义AlertDialog

  1. /**

  2. * 自定义的对话框

  3. */

  4. public abstract class MyAlerDialog extends AlertDialog implements

  5. android.view.View.OnClickListener {

  6. protected MyAlerDialog(Context context) {

  7. super(context);

  8. // TODO Auto-generated constructor stub

  9. }

  10. /**

  11. * 布局中的其中一个组件

  12. */

  13. private TextView txt;

  14. @Override

  15. protected void onCreate(Bundle savedInstanceState) {

  16. // TODO Auto-generated method stub

  17. super.onCreate(savedInstanceState);

  18. // 加载自定义布局

  19. setContentView(R.layout.dialog);

  20. // setDialogSize(300, 200);

  21. txt = (TextView) findViewById(R.id.tv1);

  22. txt.setOnClickListener(this);

  23. }

  24. /**

  25. * 修改 框体大小

  26. *

  27. * @param width

  28. * @param height

  29. */

  30. public void setDialogSize(int width, int height) {

  31. WindowManager.LayoutParams params = getWindow().getAttributes();

  32. params.width = 350;

  33. params.height = 200;

  34. this.getWindow().setAttributes(params);

  35. }

  36. public abstract void clickCallBack();

  37. /**

  38. * 点击事件

  39. */

  40. @Override

  41. public void onClick(View v) {

  42. // TODO Auto-generated method stub

  43. if (v == txt) {

  44. clickCallBack();

  45. }

  46. }

  47. }

在活动中使用:

[html] view plaincopyprint?Android自定义AlertDialogAndroid自定义AlertDialog

  1. MyAlerDialog mydialog = new MyAlerDialog(this) {

  2. // 重写callback方法

  3. @Override

  4. public void clickCallBack() {

  5. // TODO Auto-generated method stub

  6. btn.setText("call");

  7. }

  8. };

  9. mydialog.show();

自己写的功能就封装了两个,有需要的童鞋可以很容易的扩展。这种方法,显然相对于上一种要有优势得多啦。