<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rel" 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" tools:context=".MainActivity"> <Button android:id="@+id/but" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="换色" android:background="@drawable/ic_launcher_background" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textSize="50sp" android:textColor="#000000" > </Button></RelativeLayout>MainActivity
package com.example.color;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import android.content.DialogInterface;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.Toast;public class MainActivity extends AppCompatActivity { Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inter(); View.OnClickListener but1=new but1(); but.setOnClickListener(but1); } public void inter(){ but=findViewById(R.id.but); } class but1 implements View.OnClickListener{ String bj="#ffffff"; public void onClick(View view){ AlertDialog dialog; AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this) .setTitle("设置主题背景") .setIcon(R.drawable.ic_launcher_background) .setSingleChoiceItems(new String[]{"红", "橙", "黄", "绿",}, 2, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch(i){ case 0:bj="#fff44336"; break; case 1:bj="#ff9800"; break; case 2:bj="#ffeb3b"; break; case 3:bj="#87f332"; break; } } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { ((RelativeLayout)findViewById(R.id.rel)).setBackgroundColor (Color.parseColor(bj)); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); dialog=builder.create(); dialog.show(); } }}