操作环境
- Windows 10
- Android Developer Tools (Build: v22.2.1-833290)
- Android 4.3
代码
res/layout/activity_main.xml 代码如下:
<pre class="wp-block-code"><code><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:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="90dp" android:text="点击开启一个对话框" android:onClick="onclick" /> </RelativeLayout></code></pre>
src/com/example/duihuakuang/MainActivity.java 代码如下:
package com.example.duihuakuang; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onclick(View view) { AlertDialog.Builder builder = new Builder(this); builder.setIcon(null);//设置图标, 这里设为空值 builder.setTitle("ZhaoKaifeng.com"); builder.setMessage("确定要取消吗"); builder.setPositiveButton("确定", new OnClickListener(){ public void onClick(DialogInterface arg0, int arg1){ Toast.makeText(MainActivity.this,"确定成功!",Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("取消", new OnClickListener(){ public void onClick(DialogInterface arg0,int arg1){ Toast.makeText(MainActivity.this, "取消成功!", Toast.LENGTH_SHORT).show(); } }); AlertDialog b = builder.create(); b.show();//显示对话框 } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
运行效果
程序首页效果:
点击“点击开启一个对话框”按钮后的效果:
点击“确定”按钮后的效果:
点击“取消”按钮后的效果: