The problem and solution of Button background color cannot be modified in Android development

Table of contents

        question:

        problem causes:

        Solution:


        In Android, Button is a button component that the user can click on to trigger a corresponding event handler.       

         When developing Android, you need to use buttons, but for beginners, the buttons at the beginning are the default theme colors, no matter how you modify them, they will not change the color, so record the pits you have stepped on here.

question:

When using Android Studio for android development, whether it is a dragged Button or a Button you set yourself, the background color of the Button cannot be modified, and the default purple color of the system appears.

Take a Button as an example, the code:

<Button
        android:id="@+id/button4"
        android:layout_width="143dp"
        android:layout_height="80dp"
        android:background="@drawable/shapge_1"
        android:text="Button"
        tools:layout_editor_absoluteX="160dp"
        tools:layout_editor_absoluteY="317dp" />

db64f78de7c04334a46c288566d8f311.png

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="50dp"/>
    <gradient android:startColor="#ff0000"
        android:centerColor="#00ff00"
        android:endColor="#0000ff"
        android:angle="0"/>

</shape>

2c401816ee2744348868c9f9e7d3d0e4.png

 The preview button should be colored, but it is still the default color:

c6f0ae07928443cc8a7a1dec8f93d769.png

problem causes:

        The main reason for this problem is that when using Android Studio 4.1 or later for development, all Buttons in the default theme of the created project are Material type Buttons, and the theme color is used by default, so if you want to modify the color, you must change the default theme closed or replaced.

Solution:

method one:

<Button
        android:id="@+id/button4"

 

Change to -------->

 

<android.widget.Button
        android:id="@+id/button4"

<Button
        android:id="@+id/button4"

改为-------->

<android.widget.Button
        android:id="@+id/button4"

Method 2:

Find the temes.xml file

Put this code:
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">


修改为:
---------->
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">

After the modification, the Button background color appears:

62098a717b3f4721bf507b3b3889b8db.png

 

Guess you like

Origin blog.csdn.net/m0_61961937/article/details/127087503
Recommended