Main.xml
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical">
<Button android:id="@+id/mybut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出单选对话框"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
Main.java
package com.example.singlechoicedialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取我们的按钮,文本
Button but=(Button) super.findViewById(R.id.mybut);
final TextView textView=(TextView) super.findViewById(R.id.textView);
final Builder b=new AlertDialog.Builder(this);
//为按钮绑定点击事件
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.setIcon(R.drawable.ic_launcher);
b.setTitle("单选列表对话框");
b.setNegativeButton("确定", null);
b.setSingleChoiceItems(new String[]{
"红色","绿色","蓝色"
}, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case 0:
textView.setBackgroundColor(Color.RED);
break;
case 1:
textView.setBackgroundColor(Color.GREEN);
break;
case 2:
textView.setBackgroundColor(Color.BLUE);
break;
}
}
});
b.create().show();
}
});
}
}