自己封装的一个简单的对话框,按钮监听也加上了
package com.example.utils;
import com.example.dialog.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/********************
* info:自定义对话框
* author:xgw
* date:2014年01月24日
*
* *********************/
public class MyDialog extends Activity {
static Button btn, yes, no;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public static void showdialog(final Context context) {
AlertDialog.Builder builder;
final AlertDialog dialog;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dialog, null);
builder = new AlertDialog.Builder(context);
builder.setView(view);
dialog = builder.create();
dialog.show();
yes = (Button) view.findViewById(R.id.yes);
yes.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
Toast.makeText(context, "恭喜你选择了确定", Toast.LENGTH_SHORT).show();
}
});
no = (Button) view.findViewById(R.id.no);
no.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
Toast.makeText(context, "您选选择了取消", Toast.LENGTH_SHORT).show();
}
});
}
}
布局文件
<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"
android:background="#99ad88"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定要退出吗"
android:id="@+id/title"
/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="center_horizontal"
android:layout_below="@+id/title"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定"
android:id="@+id/yes"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"
android:id="@+id/no"
/>
</LinearLayout>
</RelativeLayout>
调用方法,我这里是订一个的一个button,点击的时候弹出来对话框。
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// new Dialog.show(MainActivity.this);
//这里是调用的
new MyDialog().showdialog(MainActivity.this);
}
});
效果图