如何设置RelativeLayout背景颜色?

时间:2016-10-22 02:29:55

标签: java android android-layout

我正在尝试设置RelativeLayout backgroundColor,但我无法解析符号

这是我的代码

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);

        }

     }

 }

一切都运行良好,直到color无效。错误是cannot resolve symbol但有趣的是我可以在空白之前使用layout.setBackgroundColor()设置颜色。

所以问题是,你如何设置一个布局backgroudColor?

2 个答案:

答案 0 :(得分:1)

使用此:

layout1.setBackgroundColor(ContextCompat.getColor(this, R.color.black)); 

layout1.setBackgroundColor(Color.parseColor("#000000"));

答案 1 :(得分:1)

您的RelativeLayout位于onCreate() 方法范围中,您必须将其移至类范围。像这样:

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.
    }
  }