Java app setBackground()错误:不兼容的类型:int无法转换为可绘制的

Java app setBackground()错误:不兼容的类型:int无法转换为可绘制的,java,android,android-layout,int,drawable,Java,Android,Android Layout,Int,Drawable,在一个非常简单的应用程序中,点击一个按钮就可以改变背景颜色,我遇到了一个无法使用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

在一个非常简单的应用程序中,点击一个按钮就可以改变背景颜色,我遇到了一个无法使用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>

#008577
#00574B
#D81B60
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文件中设置背景时,line view.setBackground(R.color.colorAccent)会弹出以下错误:

错误:不兼容的类型:int无法转换为可绘制


我应该如何解决此错误?

它可能应该是
view.setBackgroundResource(R.color.colorAccent)

与AppCompatActivity一起使用:

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


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

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