package com.example.zzl; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { String[] a = {"#CC3300", "#FFFF00", "#3300FF", "#33CC33", "#9900CC"}; int b = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); the setContentView (R.layout.activity_main); } public void Test (View View) { AlertDialog Dialog; AlertDialog.Builder Builder = new new AlertDialog.Builder ( the this ) .setTitle ( "set the background color") // provided the title .setIcon (R.drawable.ic_launcher_background) .setSingleChoiceItems ( new new String [] { "red", "yellow", "blue", "green", "purple"}, B, new new DialogInterface. OnClickListener() { public void onClick(DialogInterface dialog, int Which) { // event that occurs when the point radio buttons, radio buttons showing Which here you are several points B = Which; } }) .setPositiveButton ( "OK", new new DialogInterface.OnClickListener () { @ override public void the onClick (DialogInterface Dialog, int Which) { // event that occurs when the point determination button the findViewById (R.id.rl1) .setBackgroundColor (Color.parseColor (a [B])); dialog.dismiss (); } }) //Add "OK" button .setNegativeButton ( "Cancel", new new DialogInterface.OnClickListener () { @Override public void the onClick (DialogInterface Dialog, int Which) { // point cancel button event occurred dialog.dismiss (); } }); Dialog = Once builder.create (); with dialog.show (); } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/rl1" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点我" android:textSize="39sp" android:background="#66cccccc" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:onClick="test" /> </RelativeLayout>