自定义AlertDialog

常见的一种方法:

AlertDialog.Builder builder;
				AlertDialog alertDialog;

				LayoutInflater inflater = getLayoutInflater();
				// 添加自定义的布局文件
				View layout = LayoutInflater.from(TestOne.this).inflate(
						R.layout.dialog, null);
				final TextView text = (TextView) layout.findViewById(R.id.tv1);
				// 添加点击事件
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						text.setText("call");
					}
				});

				builder = new AlertDialog.Builder(TestOne.this);
				alertDialog = builder.create();
				// 去掉边框的黑色,因为设置的与四周的间距为0
				alertDialog.setView(layout, 0, 0, 0, 0);
				alertDialog.show();
				// 修改大小
				WindowManager.LayoutParams params = alertDialog.getWindow()
						.getAttributes();
				params.width = 350;
				params.height = 200;
				alertDialog.getWindow().setAttributes(params);

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



重写AlertDialog类,定义方法:

/**
 * 自定义的对话框
 */
public abstract class MyAlerDialog extends AlertDialog implements
		android.view.View.OnClickListener {

	protected MyAlerDialog(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 布局中的其中一个组件
	 */
	private TextView txt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 加载自定义布局
		setContentView(R.layout.dialog);
		// setDialogSize(300, 200);
		txt = (TextView) findViewById(R.id.tv1);
		txt.setOnClickListener(this);
	}

	/**
	 * 修改 框体大小
	 * 
	 * @param width
	 * @param height
	 */
	public void setDialogSize(int width, int height) {
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.width = 350;
		params.height = 200;
		this.getWindow().setAttributes(params);
	}

	public abstract void clickCallBack();
	
	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == txt) {
			clickCallBack();
		}
	}

}

在活动中使用:

MyAlerDialog mydialog = new MyAlerDialog(this) {
			// 重写callback方法
			@Override
			public void clickCallBack() {
				// TODO Auto-generated method stub
				btn.setText("call");
			}
		};
		mydialog.show();
自己写的功能就封装了两个,有需要的童鞋可以很容易的扩展。这种方法,显然相对于上一种要有优势得多啦。

你可能感兴趣的:(对话框,可扩展)