Mr.Benson
Mr.Benson

Reputation: 169

app setBackground() error: incompatible types: int cannot be converted to Drawable

Working on a very simple app to change color of background upon clicking a button, I am stuck at a bug where the color of background is unable to be changed using MainActivity.java file.

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>

When setting the background in MainActivity.java file, the following error pops up for the line view.setBackground(R.color.colorAccent);

error: incompatible types: int cannot be converted to Drawable

What should I do to resolve this bug?

Upvotes: 4

Views: 4793

Answers (3)

Abderazak Amiar
Abderazak Amiar

Reputation: 808

With AndroidX, you have to use yourContext.getResources().getColor(R.color.yourColor) instead of (R.color.yourColor)

Upvotes: 1

ronginat
ronginat

Reputation: 2005

Works with AppCompatActivity:

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

and

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

Upvotes: 1

Rakhi Dhavale
Rakhi Dhavale

Reputation: 1206

It should probably be view.setBackgroundResource(R.color.colorAccent);

Upvotes: 3

Related Questions