首页 > 解决方案 > 使用属性以编程方式线性布局设置背景颜色

问题描述

我有一个警报对话框生成器,我在其中以编程方式定义布局。我有一个线性布局,我想设置一个属性,所以在运行时我可以更改应用程序的颜色主题。我正在让大多数事情正常工作,但我无法弄清楚如何进行线性布局,因为它没有在 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>

有没有办法将属性设置为线性布局背景颜色?我需要它是动态的,所以我可以在运行时更改它。它不能在那里硬编码

标签: javaandroidandroid-alertdialog

解决方案


尝试这个:

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);
}

推荐阅读