Android之AlertDialog对话框
主函数:
package com.example.alertdialog;import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button2);
// Button1事件监听
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("您的手机已中毒!!!");
builder.setIcon(R.drawable.icon);
builder.setMessage("请立即前往杀毒");
builder.setPositiveButton("是",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "让你瞎点 中毒了吧",
Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("否",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,
"十秒钟后自动关机...", Toast.LENGTH_SHORT)
.show();
}
});
//禁止按返回键退出对话框
builder.setCancelable(false);
builder.show();
}
});
// Button2事件监听
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "怂..........",
Toast.LENGTH_LONG).show();
}
});
}
}
--------------------------------------------------------------------
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_gravity="center"
android:text="点我"
android:textSize="130sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:text="就不点"
android:textSize="35sp"/>
</LinearLayout>