【问题标题】:not able to change button color with onClick event, button becomes purple无法通过 onClick 事件更改按钮颜色,按钮变为紫色
【发布时间】:2021-06-07 23:18:47
【问题描述】:

一旦按下按钮,我想将按钮的颜色更改为我在颜色/可绘制对象中创建的任何颜色,但按钮并没有按预期改变。我想我在这个网站上尝试了一切,但找不到解决方案。 android:backgroundTint 没有成为解决方案。我只想将颜色更改为我创建的任何颜色,而不是紫色。

<Button
    android:id="@+id/button"
    android:layout_width="254dp"
    android:layout_height="62dp"
    android:background="@color/white"
    android:text="Press"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.496"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.857" />

主题;

<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.YdsYokdil" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/purple_500</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>
    <item name="colorOnPrimary">@color/white</item>
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_700</item>
    <item name="colorOnSecondary">@color/black</item>
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>    
</style>

主题(夜晚)

<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.YdsYokdil" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/purple_200</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>
    <item name="colorOnPrimary">@color/black</item>>
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_200</item>
    <item name="colorOnSecondary">@color/black</item>
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
</style>

我的代码(改变颜色)

var isRedButtonsClicked = true

    fun colorButtonsRed() {
        binding.button.setBackgroundColor(R.color.red)
    }
     binding.button.setOnClickListener {
        when (isRedButtonsClicked) {
            true -> colorButtonsRed()
        } 
        setContentView(binding.root)

【问题讨论】:

  • 另外,onClickListenet 中的setContentView 很奇怪,不需要
  • @Amin 当我删除setContentView(binding.root) 应用程序没有打开,出现白屏。不知道这两个有没有关系

标签: android kotlin android-layout data-binding onclick


【解决方案1】:

setBackgroundColor 需要一个颜色 int(例如,0xFFFF0000 是 argb 格式的红色)R.color.red 是一个 ColorRes(来自 R 的资源标识符)

为了从R.color.xxx 中获取颜色,我们应该使用ContextCompat.getColor(context, R.color.xxx)

所以把你的代码改成

fun colorButtonsRed() {
    binding.button.setBackgroundColor(
        ContextCompat.getColor(context, R.color.red)
    )
}

【讨论】:

  • '(context, R.color.red)' 上下文在这里做什么?它给出错误
  • 好吧,我应该推荐(上下文:this,R.color.red)你是救世主!谢谢。这是有效的。 :)
猜你喜欢
  • 2015-01-12
  • 1970-01-01
  • 2018-04-03
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多