MainActivity.java
package com.example.simplealertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.tv);
final String[] items = new String[] { "1", "2", "3" };
final Builder builder = new AlertDialog.Builder(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
builder.setIcon(R.drawable.ic_launcher);
// builder.setMessage("nothing");//message和列表的位置是冲突的 写上的话会显示message 无论放在哪
builder.setTitle("title");
//在点击时候创建一个对话框
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
tv.setText("1");
break;
case 1:
tv.setText("2");
break;
case 2:
tv.setText("3");
break;
}
}
});
// builder.setMessage("nothing");//message和列表的位置是冲突的 写上的话会显示message
//点击时候创建
builder.create().show();
}
});
}
}
activity_main.xml
<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" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我 "
/>
</LinearLayout>