java - 使用属性以编程方式线性布局设置背景颜色
问题描述
我有一个警报对话框生成器,我在其中以编程方式定义布局。我有一个线性布局,我想设置一个属性,所以在运行时我可以更改应用程序的颜色主题。我正在让大多数事情正常工作,但我无法弄清楚如何进行线性布局,因为它没有在 xml 中定义。
我确实有一个硬编码 i 的十六进制颜色代码,但这不是我想要的。有没有办法设置像 ?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);
我正在尝试访问主题属性
<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>
有没有办法将属性设置为线性布局背景颜色?我需要它是动态的,所以我可以在运行时更改它。它不能在那里硬编码
解决方案
尝试这个:
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);
}
推荐阅读
- php - 生成除php中指定数字外的随机数
- html - 如何获取清除输入字段的 CSS 选择器?
- spring-boot - Kafka Streams以编程方式配置不起作用
- reactjs - 在反应如何从 model.ts 调用属性
- c# - 无法反序列化多层 XML
- excel - SSIS 中的 Excel 导出
- excel - Excel IF 语句,具有 3 个条件 if a=true and b=true and c=true then d1 = ""
- python - 时间序列图:xarray 中多年的 Groupby 季节(或特定月份)
- reactjs - React Hook useEffect 缺少依赖项 - 问题
- reactjs - React.useContext 未定义