开发者

Android First App, changing the background color from a list of specified colors

开发者 https://www.devze.com 2022-12-18 21:47 出处:网络
This is my first app so finding my way around bit by bit and have been experimenting a little and would like to change the background colour to a colour from a list.

This is my first app so finding my way around bit by bit and have been experimenting a little and would like to change the background colour to a colour from a list.

Currently it loads a white background specified in strings.xml

<color name="all_white">#FFFFFF</color> 

This is used in main.xml:

android:background="@color/all_white"

Ideally I would like to change the colour in OnCreate() to a colour of my choice. I have tried setBackgroundDrawable but it doesnt seem to work?

This is my code:

public class TestActivity extends Activity 
{
 double dimValPercent = 100;

    /** Called when the activity is first created. */
    @Override
    public 开发者_StackOverflowvoid onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SetDimLevel(dimValPercent);
        SetBackground();
        return;
    }

    public void SetBackground()
    {
     getWindow().setBackgroundDrawable( new ColorDrawable
       (color.all_blue) );   
     return;
    }



   void SetDimLevel(double dimVal)
   {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
       lp.screenBrightness = (float) (dimVal/ 255.0);
       getWindow().setAttributes(lp);
       return;
   }
}


In Android, a view has setBackgroundColor(int) which you can use to change the color of a background. Try using that instead of setBackgroundDrawable(). I suspect that you will have to do it on the UI thread as well, so you might have to use one of the post (Runnable action) methods. For example:

view.post(new Runnable() {
    @Override
    public void run() {
        view.setBackgroundColor(Color.BLACK);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号