有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java app setBackground()错误:不兼容的类型:int无法转换为Drawable

在一个非常简单的应用程序中,点击一个按钮就可以改变背景颜色,我遇到了一个无法使用MainActivity改变背景颜色的错误。java文件

package com.example.audio;

import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.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);
    }
}

颜色。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>

主要活动。xml

<?xml version="1.0" encoding="utf-8"?>
<安卓.support.constraint.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    tools:context=".MainActivity">

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

在MainActivity中设置背景时。java文件,线视图会弹出以下错误。挫折背景(R.color.colorAccent)

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

我应该如何解决此错误


共 (1) 个答案

  1. # 1 楼答案

    使用AppCompative活动:

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

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