How do I programmatically set the background color gradient on a Custom Title Bar?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

There are many tutorials out there and questions on SO that implement custom title bars. However, in my custom title bar I have a custom gradient for the background and I would like to know how to set it dynamically in my code.

Here is where my custom title bar gets called:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.foo_layout); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar);  

And this is my custom_title_bar:

As you can see, the background on the linear layout is defined by this guy:

What I would like to do is set those gradient colors dynamically in my code. I do not want to hard code them in my XML file like they currently are.

I am open to all ideas if you have a better way of setting a background gradient.

Thank you in advance!!

回答1:

To do this in code, you create a GradientDrawable.
The only chance to set the angle and color is in the constructor. If you want to change the color or angle, just create a new GradientDrawable and set it as the background

    View layout = findViewById(R.id.mainlayout);      GradientDrawable gd = new GradientDrawable(             GradientDrawable.Orientation.TOP_BOTTOM,             new int[] {0xFF616261,0xFF131313});     gd.setCornerRadius(0f);      layout.setBackgroundDrawable(gd); 

For this to work, I added an id to your main LinearLayout as follows

And to use this as for a custom title bar

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title_bar);     View title = getWindow().findViewById(R.id.mainlayout);     title.setBackgroundDrawable(gd); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!