[英]Programatically Linearlayout set background color using attribute
I have an alert dialog builder where i am defining the layout programatically. 我有一个警报对话框生成器,可以在其中以编程方式定义布局。 I have a linear layout that I want to set an attribute to so at runtime i can change the color theme of the app.
我有一个线性布局,我想设置一个属性,以便在运行时可以更改应用程序的颜色主题。 I am getting most things to work but I cant figure out how to do the linear layout since its not defined in xml.
我正在做大多数事情,但是我无法弄清楚如何进行线性布局,因为它不是在xml中定义的。
I do have a hex color code hardcoded i, but thats not what i want. 我确实有一个硬编码的十六进制颜色代码,但这不是我想要的。 Is there a way to set an attribute like ?attr/colorPrimary
有没有办法设置诸如attr / colorPrimary之类的属性?
alertAFFY = new AlertDialog.Builder(AddMakeActivity.this);
LinearLayout mainLayout = new
LinearLayout(AddMakeActivity.this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout layoutTitle = new LinearLayout(AddAlarmActivity.this);
layoutTitle.setOrientation(LinearLayout.HORIZONTAL);
TextView title = new TextView(getApplicationContext());
title.setPadding(0, 30, 0, 30);
title.setTextColor(Color.parseColor("#FFFFFF"));
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
title.setText("Select One");
layoutTitle.setGravity(Gravity.CENTER_HORIZONTAL);
layoutTitle.addView(title);
**// i need to change the background color to take in ?attr/ **
layoutTitle.setBackgroundColor(Color.parseColor("#F8B195"));
layoutTitle.setMinimumHeight(20);
mainLayout.addView(layoutTitle);
I am trying to access the theme attribute 我正在尝试访问主题属性
<style name="Theme1" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/toolbarColor</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorDays">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
</style>
is there a way to set an attribute to the linear layout background color? 有没有一种方法可以将属性设置为线性布局背景色? I need it to be dynamic so i can change it at runtime.
我需要它是动态的,以便我可以在运行时更改它。 It cant be hardcoded in there
它不能在那里硬编码
Try this: 尝试这个:
TypedValue typedValue = new TypedValue();
getApplicationContext().getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
// it's probably a good idea to check if the color wasn't specified as a resource
if (typedValue.resourceId != 0) {
layoutTitle.setBackgroundResource(typedValue.resourceId);
} else {
// this should work whether there was a resource id or not
layoutTitle.setBackgroundColor(typedValue.data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.