如何声明自定义 alertDialog static class?

How to declare a custom alertDialog static class?

我有这个布局。

http://imgur.com/Yk0ax7G

我想创建一个 class 来显示此布局和一个关闭按钮。我这样试过。

   public static class CounterDialog extends AlertDialog.Builder{

    public CounterDialog(Context context) {
        super(context);
    }
}

但我不知道应该在哪里声明按钮和 onClickListener,所以它们去哪里了?在构造函数中?我也应该在哪里设置 setTitle、setCancelable、setButton 属性?谢谢!

您可以在 constructor.Here 中声明按钮和 onclickListener 方法是我的代码:

public static class CounterDialog extends AlertDialog.Builder{
    private TextView textView;

    public CounterDialog(Context context) {
        super(context);

        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog, null);
        setView(view);

        setTitle("mytitile!");

        textView = (TextView)view.findViewById(R.id.textView);

        Button button = (Button)view.findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                textView.setText("click me!!!");


            }
        });
    }     

}

这是我的 xml(自定义对话框 xml):

R.layout.dialog:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center" >
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hahahaahahaha"
    android:textSize="20sp"
    />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="click me!"
    android:gravity="center"
    android:layout_marginTop="10dp"
    />
 </LinearLayout>

您可以使用以下方法创建自定义对话框:

CounterDialog counterDialog = new CounterDialog(this);
counterDialog.show();

"this" 是您的 activity 的实例。而setTitle、setCancelable可以在构造函数中直接调用。