【问题标题】:Changing button color causes the button to get bigger更改按钮颜色会导致按钮变大
【发布时间】:2018-04-28 06:21:35
【问题描述】:

Here is what the button looks like after changing the color

Here is what it looks like with "show layout bounds" on

我有一个“添加注释”按钮,它显示一个对话框供用户输入注释。

如果保存了笔记,我想更改按钮的颜色。

我试过了:

btnNote.setBackgroundColor(view.getContext().getResources().getColor(R.color.NN));

还有这个:

btnNote.getBackground().setColorFilter(ContextCompat.getColor(view.getContext(), R.color.NN), PorterDuff.Mode.MULTIPLY);

但在这两种情况下,按钮也会变得稍大。

如何只更改按钮的颜色?

这是我的布局文件中的按钮:

<Button
    android:id="@+id/btnNote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="Add note"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/btnDelete"
    app:layout_constraintTop_toTopOf="parent" />

【问题讨论】:

  • 在其中添加一些填充,然后在更改颜色期间大小不会调整大小
  • 我添加了android:padding="2dp",但这并没有改变结果
  • 改变高度一旦达到 50 dp
  • 我试过了,结果是一样的
  • 然后使用一次这个 btnNote.setBackgroundResource(Color.parse(colorName));

标签: android button


【解决方案1】:

我已经尝试了所有选项,最后它可以正常工作,我在您的 XML Button 视图中使用 android:backgroundTint 属性。

在片段下方显示:-

android:backgroundTint="#6567dc"

有问题

如果在您的 gradle 文件中 minSdkVersion 低于 21,则您应该将其更改为 21 您可以 将代码包装到 if 条件中,检查设备 SDK 支持如下

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            btnAccept.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.yourcolor));
        }

使用上面的代码输出:

颜色改变后

【讨论】:

    【解决方案2】:

    我觉得没变大,你可以在开发者选项中打开“显示布局绑定”开关,按钮的布局没有改变,你可以自定义一个drawable作为背景。

    【讨论】:

    • 我试过了,你说得对,界限没有变大(见我添加到问题中的第二张截图)。但是当颜色改变时按钮会变大
    • 我将为背景制作一个自定义可绘制对象并检查结果
    • 谢谢,这就是解决方案
    【解决方案3】:

    不要使用background,试试backgroundTint

    在xml中,

    android:backgroundTint="#yourcolor"
    

    在java中,

    setBackgroundTintList(ColorStateList list)

    对于AppCompatButton

    button.setSupportBackgroundTintList(ContextCompat.getColorStateList(this, R.color.yourcolor));
    

    你可以使用,

     ViewCompat.setBackgroundTintList(AppCompatButton, ColorStateList)
    

    【讨论】:

    • 我想使用它,但它说它需要 API 21,我正在为 API 16 构建。
    • 然后您可以使用 appcompat 按钮并使用编辑后的答案
    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2018-03-23
    • 2020-08-03
    • 2014-07-11
    相关资源
    最近更新 更多