列表对话框
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bn = (Button)findViewById(R.id.bn);
final Builder b = new AlertDialog.Builder(this);
//为按钮绑定事件监听器
bn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View source)
{
//设置对话框的图标
b.setIcon(R.drawable.tools);
//设置对话框的标题
b.setTitle("简单列表对话框");
//为对话框设置多个列表
b.setItems(
new String[] {"红色" , "绿色" , "蓝色"}
//为按钮设置监听器
, new OnClickListener()
{
//该方法的which参数代表用户单击了那个列表项
@Override
public void onClick(DialogInterface dialog
, int which)
{
TextView show = (TextView)
findViewById(R.id.show);
//which代表哪个列表项被单击了
switch(which)
{
case 0:
show.setBackgroundColor(Color.RED);
break;
case 1:
show.setBackgroundColor(Color.GREEN);
break;
case 2:
show.setBackgroundColor(Color.BLUE);
break;
}
}
});
//创建、并显示对话框
b.create().show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="测试文本内容"
android:textSize="11pt" />
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择颜色" />
</LinearLayout>
setItems(CharSequence[], OnClickListener) 设置对话框列表
b.setItems(new String[] {"红色" , "绿色" , "蓝色"}
, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog
, int which)
{
TextView show = (TextView) findViewById(R.id.show);
switch(which)
{
case 0: show.setBackgroundColor(Color.RED);
break;
case 1: show.setBackgroundColor(Color.GREEN);
break;
case 2: show.setBackgroundColor(Color.BLUE);
break;
}
}
});