我们先看下面的弹出框如何实现:
xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/title" android:layout_width="match_parent" android:layout_height="60dp" > <TextView android:id="@+id/content" android:layout_width="match_parent" android:layout_marginTop="20dp" android:layout_height="60dp" android:layout_marginLeft="25dp" android:text="@string/upgrade_content" android:textColor="#000000" android:textSize="22sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:layout_below="@id/content" android:orientation="horizontal" > <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="15dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="15dp" android:text="@string/remind_me" android:textColor="#000000" android:textSize="14sp" /> </LinearLayout> </RelativeLayout>
代码实现:
public AlertDialog getEditCustomDialog(String leftText,android.content.DialogInterface.OnClickListener leftlistener, String rightText, android.content.DialogInterface.OnClickListener rightlistener) { LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.test_dialog1, null); AlertDialog.Builder builder = new AlertDialog.Builder(DialogTest.this); if (!TextUtils.isEmpty(leftText)) { builder.setNegativeButton(leftText, leftlistener); } if (!TextUtils.isEmpty(rightText)) { builder.setPositiveButton(rightText, rightlistener); } builder.setView(view); builder.setTitle("A New Version is Available"); return builder.create(); }
Dialog dialog = getEditCustomDialog("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("TAG","<<<<left "); } }, "Upgrade Now", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("TAG","<<<<right "); } }); //是否可以点击硬件的back让弹出框消失 dialog.setCancelable(true); //是否点击弹出框的空白部分可以让弹出框消失 dialog.setCanceledOnTouchOutside(true);
我们可以在dialog.show以后通过WindowManager来改变框的大小
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); lp.width = DialogTest.this.getResources().getDimensionPixelSize(R.dimen.dialog_width); lp.height = DialogTest.this.getResources().getDimensionPixelSize(R.dimen.dialog_height); dialog.getWindow().setAttributes(lp);