【问题标题】:app setBackground() error: incompatible types: int cannot be converted to Drawableapp setBackground() 错误:不兼容的类型:int 无法转换为 Drawable
【发布时间】:2019-08-22 22:07:58
【问题描述】:

在一个非常简单的应用程序上工作以在单击按钮时更改背景颜色,我遇到了一个错误,即无法使用 MainActivity.java 文件更改背景颜色。

package com.example.audio;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    View view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view = this.getWindow().getDecorView();
        view.setBackground(R.color.colorAccent);
    }
}

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

在MainActivity.java文件中设置背景时,view.setBackground(R.color.colorAccent);这一行弹出如下错误

错误:不兼容的类型:int 无法转换为 Drawable

我应该怎么做才能解决这个错误?

【问题讨论】:

  • 使用view.setBackgroundResource(R.color.colorAccent);

标签: java android android-layout int drawable


【解决方案1】:

应该是view.setBackgroundResource(R.color.colorAccent);

【讨论】:

    【解决方案2】:

    适用于 AppCompatActivity:

    view.setBackground(ContextCompat.getDrawable(context, R.color.colorAccent));
    

    view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorAccent));
    

    【讨论】:

      【解决方案3】:

      对于 AndroidX,您必须使用 yourContext.getResources().getColor(R.color.yourColor) 而不是 (R.color.yourColor)

      【讨论】:

        猜你喜欢
        • 2017-10-03
        • 2018-05-28
        • 1970-01-01
        • 2016-09-05
        • 2023-01-18
        • 2017-03-29
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        相关资源
        最近更新 更多