Eddie Eddie - 1 month ago 20
Android Question

How to set a RelativeLayout backgroud color

I am trying to set a RelativeLayout backgroundColor and I get cannot resolve symbol

here is my code

package com.example.butka.clickme;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import java.util.Random;

public class MainActivity extends AppCompatActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
//set layout
super.onCreate(savedInstanceState);
RelativeLayout layout1 = new RelativeLayout(this);
layout1.setBackgroundColor(Color.BLACK);

//LayoutParameters
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);

params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.CENTER_VERTICAL);

//button
Button btn = new Button(this);
btn.setText("Click me");
btn.setBackgroundColor(Color.WHITE);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
colors();
}
});

//add stuff
layout1.addView(btn, params);
setContentView(layout1);

}

//void on button click
private void colors()
{
Random random = new Random();
short num1 = (short)random.nextInt(9);

if(num1 == 0)
{
layout1.setBackgroundColor(Color.BLACK);

}

}

}


everything runs good, until the
color
void. the error is
cannot resolve symbol
But the interesting thing is that I can set the color using
layout.setBaclgroudClor()
before the void.

So the question is, how do you set a layout backgroudColor?

Answer

Your RelativeLayout is in the onCreate() method scope, you must move it to class scope. Like this:

public class MainActivity extends AppCompatActivity {  
  RelativeLayout layout1;  // Make it class scope.

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    //set layout
    super.onCreate(savedInstanceState);
    RelativeLayout layout1 = new RelativeLayout(this);
    layout1.setBackgroundColor(Color.BLACK);
    ...
  }

  // Then you can access it from other method:
  private void colors() {
    Random random = new Random();
    short num1 = (short)random.nextInt(9);

    if(num1 == 0) {
       layout1.setBackgroundColor(Color.BLACK); // You can access it now.
    }
  }
Comments