【问题标题】:Android - Set background view for whole app dynamicallyAndroid - 动态设置整个应用程序的背景视图
【发布时间】:2014-12-05 05:01:46
【问题描述】:

我使用以下代码设置了我的应用的背景颜色:

RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.RED);

如果不使用 XML,我怎么能将其延续到此活动之后的下一个活动,因为它并不总是红色。这取决于用户的选择。但是一旦用户选择了红色,我希望这种颜色能够延续到下一个活动。有没有办法在不为所有活动者做这样的事情的情况下解决这个问题。

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "RED");
startActivity(intent);

然后在下一个活动中使用该 Extra 设置颜色。有没有一种方法可以只为以下所有活动设置它,直到用户更改它?

提前感谢您的帮助。

【问题讨论】:

标签: java android xml android-intent colors


【解决方案1】:

我认为您需要获取该颜色的#Code 并使用

发送价值

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "#Code");
startActivity(intent);

在下一个活动中..

RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.parseColor(intent.getExtra("Color")));

【讨论】:

    【解决方案2】:

    android 中使用的颜色是int 格式而不是String

    setBackgroundColor() takes a color in numeric form (e.g., 0xFFFF0000 for red)


    所以你可以这样做:

    假设从class A发送一个int变量到class B

    int bgColor=Color.RED; <---Change It with whatever you want(but should be numeric)
    
    Intent bgIntent = new Intent(Background.this, MainScreen.class);
    bgIntent.putExtra("background",  bgColor);
    startActivity(bgIntent);
    

    B 级

    Intent bgIntent = getIntent();
    bgGlobal = bgIntent.getExtras().getInt("background",-1);
    
    if(bgGlobal != -1) 
    {
       DetailsLayout.setBackgroundResource(Color.parseColor(bgGlobal));
    }
    else 
    {
       DetailsLayout.setBackgroundResource(R.color.a1);
    }
    

    更多信息请参考this

    【讨论】:

      【解决方案3】:

      将背景颜色的设置放在单例类中,比如说

      public class ColorHolder {
          public static ColorHolder instance=null;
          private int color;
          public static ColorHolder getInstance(){
              if(instance==null){
                  instance=new ColorHolder();
              }
          }
          public int getColor(){
              return color;
          }
          public void setColor(int c){
              color=c;
          }
      }
      

      然后创建一个Activity的子类,比如说

      public class ColoredActivity extends Activity{
          protected void onCreate(Bundle s){
              super.onCreate(s);
              RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
              rl.setBackgroundColor(ColorHolder().getInstance().getColor());
          }
      }
      

      那么所有想要应用这个设置的活动都应该扩展这个“ColoredActivity”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多