首页 > 解决方案 > 如何阻止背景颜色代码覆盖 xml 中的圆角代码?

问题描述

我在 layout.xml 中编码了以下按钮

<Button
    android:id="@+id/buttonCorrection"
    android:layout_width="0dp"
    android:layout_height="30dp"
    android:layout_marginTop="4dp"
    android:gravity="center_vertical|center_horizontal"
    android:text="Undo last entry"
    android:textSize="@dimen/button_text_size"
    android:textAllCaps="false"
    android:textColor="@color/colorAgainstBackground"
    android:background="@drawable/clickcorrectionbutton"
    app:layout_constraintEnd_toEndOf="@+id/textviewPlayerB"
    app:layout_constraintStart_toStartOf="@+id/textviewPlayerA"
    app:layout_constraintTop_toBottomOf="@+id/textviewPlayerA" />

clickcorrectionbuttion.xml 用于设置按钮的背景颜色和圆角:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <corners android:radius="10dp"></corners>
            <solid android:color="@color/colorCorrection"></solid>
        </shape>
    </item>

</selector>

这完美地工作。但是,在应用程序中的某些时候,Java 代码会要求按钮更改颜色和文本。该代码如下所示...

buttonCorrection.setBackgroundColor(getColor(R.color.colorAgainstBackground)); buttonCorrection.setTextColor(getColor(R.color.colorAgainstButton)); buttonCorrection.setText("选择按钮");

问题是,当调用该 java 代码时,它确实会根据需要更改按钮的背景颜色和文本,但它也会删除圆角。它似乎以某种方式覆盖了选择器中的内容。怎样才能让边角保持圆润?

标签: androidandroid-layout

解决方案


我为每个按钮状态制作了一个选择器 xml。背景选择 java 代码现在看起来像

buttonCorrection.setBackground(getDrawable(R.drawable.clickcorrectionbutton))

buttonCorrection.setBackground(getDrawable(R.drawable.clickcorrectionbuttonnonactive))


推荐阅读