【问题标题】:Not able to set background color to a view in Kotlin无法在 Kotlin 中为视图设置背景颜色
【发布时间】:2021-08-17 20:03:36
【问题描述】:

编辑:代码一切正常,Android Studio 未部署对应用版本 4.1.3 的更改

我正在尝试在运行时更改视图的背景颜色(相对布局和 rootView)

但这里的代码根本不起作用

rootview = findViewById(R.id.rootView)
rootview.setBackgroundColor(resources.getColor(R.color.backgroundColor2))

布局代码/文件,我在这里使用 relativeLayout 作为主要布局,它被另一个视图完全覆盖

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/rootView"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/banner_container"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        />

    <at.markushi.ui.CircleButton
        android:id="@+id/button"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_launcher_foreground"
        app:cb_color="@color/mainButtonColor1"
        app:cb_pressedRingWidth="8dip" />

    <at.markushi.ui.CircleButton
        android:layout_width="64dp"
        android:elevation="8dp"
        android:layout_height="64dp"
        android:src="@drawable/ic_launcher_foreground"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="30dp"
        android:layout_marginBottom="30dp"
        app:cb_color="#B71C1C"
        app:cb_pressedRingWidth="8dip" />



</RelativeLayout>

如果我在 XML 中设置背景,它可以正常工作

【问题讨论】:

  • 试试ContextCompat.getColor(this, R.color.yourColor)
  • 还是不行
  • @TehleelMir - 您在哪个生命周期方法中设置背景颜色?
  • 我正在测试 onCreate 方法,但它根本不起作用,在 java 中我曾经做同样的事情并且它曾经工作正常,但在 kotlin 中很奇怪

标签: android kotlin background-color


【解决方案1】:

我认为是因为您使用的是相对布局。所以也许,您的相对布局被另一个视图覆盖或覆盖(例如 view 2 被视图 1 和视图 3 覆盖)。当您更改view 2 的背景时,此功能有效,但您看不到它,因为它是covered by view 1 and view 3。您应该尝试使用 Liner Layout 进行回放。

【讨论】:

  • 我不这么认为,我已经用布局文件代码更新了答案,你现在可以看到它
  • 也许我们在resources.getColor(R.color.backgroundColor2) 中有问题。因为你的 XML 和我一起工作(我的意思是 rootview.setBackgroundColor() 工作)
猜你喜欢
  • 2019-07-19
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 2014-03-29
  • 2013-01-07
  • 2012-10-20
相关资源
最近更新 更多