接下来实现此实例:
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/layout1" android:gravity="center_horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="退出"/> </LinearLayout>
MainActivity:
package com.example.test; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button=(Button)findViewById(R.id.button1); //为"退出"按钮添加单击事件监听器 button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { AlertDialog alert=new AlertDialog.Builder(MainActivity.this).create(); alert.setIcon(R.drawable.stop); alert.setTitle("退出?"); alert.setMessage("真的要退出本软件吗?"); //添加取消按钮 alert.setButton(DialogInterface.BUTTON_NEGATIVE,"不",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); //添加"确定"按钮 alert.setButton(DialogInterface.BUTTON_POSITIVE,"是的", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { finish(); } }); alert.show(); } }); } }
运行结果如图:
转载请注明出处:http://blog.csdn.net/acmman/article/details/45022087