Android開発でボタンの背景色が変更できない問題と解決策

目次

        質問:

        問題の原因:

        解決:


        Android では、Button は、ユーザーがクリックして対応するイベント ハンドラーをトリガーできるボタン コンポーネントです。       

         Androidの開発ではボタンを使う必要がありますが、初心者の方は最初のボタンがデフォルトのテーマカラーで、いくら変更しても色が変わらないので、踏んだ穴をここに記録しておいてください。

質問:

Android Studio を使用して Android 開発を行う場合、ドラッグされた Button であろうと自分で設定した Button であろうと、Button の背景色は変更できず、システムのデフォルトの紫色が表示されます。

例としてボタンを取り上げます。コードは次のとおりです。

<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

 プレビュー ボタンは色付けする必要がありますが、デフォルトの色のままです。

c6f0ae07928443cc8a7a1dec8f93d769.png

問題の原因:

        この問題の主な原因は、開発に Android Studio 4.1 以降を使用する場合、作成されたプロジェクトのデフォルト テーマのすべてのボタンがマテリアル タイプのボタンであり、テーマ カラーがデフォルトで使用されることです。色、デフォルトのテーマを閉じたり置き換えたりする必要があります。

解決:

方法 1:

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

 

に変更-------->

 

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

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

改为-------->

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

方法 2:

temes.xml ファイルを見つけます

次のコードを入力してください:
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">


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

変更後、ボタンの背景色が表示されます。

62098a717b3f4721bf507b3b3889b8db.png

 

おすすめ

転載: blog.csdn.net/m0_61961937/article/details/127087503