<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="com.example.homework3.MainActivity" > <Button android:id="@+id/bt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="212dp" android:text="请选择颜色" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="92dp" android:text="计算机1702辛锋" android:textSize="20sp" /> </RelativeLayout>
package com.example.homework5; import android.support.v7.app.ActionBarActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends ActionBarActivity implements OnClickListener{ String[] a = {"#FFFF00", "#0000FF", "#FF0000", "#00FF00", "#9900CC"}; int color = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //设置Button监听事件 Button btn=(Button)findViewById(R.id.bt); btn.setOnClickListener(this); } @Override public void onClick(View v) { AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle("选择背景颜色") //设置标题 .setIcon(R.drawable.ic_launcher) .setSingleChoiceItems(new String[]{ "黄色", "蓝色", "红色","绿色", "紫色"}, color, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // 点单选按钮时发生的事件,这里which表示你点的单选按钮是第几个 color = which; } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //点确定按钮时发生的事件 TextView tv=(TextView) findViewById(R.id.tv); tv.setBackgroundColor(Color.parseColor(a[color])); //String类型的颜色值转换成Int类型的颜色值 dialog.dismiss(); } })//添加“确定”按钮 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点取消按钮发生的事件 dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } }