<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ly1" 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/bg" android:layout_width="wrap_content" Android: background= "Change background colors" Android: text="@drawable/et" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textColor="#00BCD4"> </Button> </RelativeLayout>
Java
package com.example.m19; 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 bg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inter(); View.OnClickListener bg1=new bg1(); bg.setOnClickListener(bg1); } public void inter(){ bg=findViewById(R.id.bg); } class bg1 implements View.OnClickListener{ String bj1="#FFFFFF"; @Override public void onClick(View view) { AlertDialog dialog; Builder AlertDialog.Builder = new new AlertDialog.Builder (MainActivity. The this ) .setTitle ( "Setting themes") // set the title .setIcon (R.drawable.et) .setSingleChoiceItems ( new new String [] { "red", "white" "black", "blue" , }, 2, new new DialogInterface.OnClickListener () { public void onClick (DialogInterface Dialog, int which) { // event that occurs when point radio buttons, which represent where you point the radio button was the first of several switch (Which) { Case 0:bj1="#FFF44336" ;break; case 1:bj1="#FFFFFF" ;break; case 2:bj1="#000000" ;break; case 3:bj1="#FF00BCD4" ;break; } } }) .setPositiveButton("确定", newDialogInterface.OnClickListener () { @Override public void onClick (DialogInterface Dialog, int Which) { // event occurs when the point of the OK button ((RelativeLayout) findViewById (R.id.ly1) ). SetBackgroundColor (Color.parseColor (bj1) ); } }) // add the "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 (); } } }