为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕无忌1623718 2022-09-14 16:08:46
在一个非常简单的应用程序上工作,在单击按钮时更改背景颜色,我陷入了一个错误,其中背景的颜色无法使用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);    }}颜色.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>在“主页活动.java文件中设置背景时,会弹出以下错误,以显示线条视图。错误:不兼容的类型:int 无法转换为可绘制我应该怎么做才能解决此错误?
查看完整描述

3 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

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



查看完整回答
反对 回复 2022-09-14
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

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



查看完整回答
反对 回复 2022-09-14
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

与应用程序兼容性活动一起使用:

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

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


查看完整回答
反对 回复 2022-09-14
  • 3 回答
  • 0 关注
  • 268 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号