还是先从最简单的开始吧,然后一步一步的扩展。
为了保证软件上所谓的低耦合度和可重用性,这里不得不需要单独建立一个类CustomerDialog,然后继承AlertDialog
public class CustomerDialog extends AlertDialog {
}
然后添加一个带Context参数的构造器,context(上下文)通俗点讲一般是指归属于那个,这里就归属于调用的那个Acitivity,也就是说这个对话框是针对调用的那个Activity
public CustomerDialog(Context context) {
super(context);
this.context = context;
}
接下来需要对AlertDialog的 onCreate方法覆盖,否则在外面就无法获得你创建的那个自定义对话框的内容了(当然你也可以直接在构造方法里调用setView,当这样一来耦合度就增加了),然后把自己的自定义内容通过setView关联进去。
@Override
protected void onCreate(Bundle savedInstanceState) {
TextView textView = new TextView(context);
textView.setText("这是一个自定义对话框");
textView.setTextSize(24);
textView.setTextColor(Color.BLACK);
setView(textView);
super.onCreate(savedInstanceState);
}
具体实现:主xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示自定义对话框" /> </RelativeLayout>