【问题标题】:Changing style works only partially: text color changes, background doesn't更改样式仅部分起作用:文本颜色更改,背景不更改
【发布时间】:2013-05-09 09:04:07
【问题描述】:

当有人点击按钮时,我正在尝试更改按钮的样式。我想将背景都更改为文本颜色。但是,仅更改了文本颜色。由此我得出结论,样式 已更改,但由于某种原因,无法覆盖背景。

我在 onClick 处理程序中使用此代码:

Button send_button = (Button) findViewById(R.id.button1);
send_button.setTextAppearance(context, R.style.activeButtonTheme);

我的styles.xml中的相关样式是:

<style name="buttonTheme">
    <item name="android:background">@color/white</item>
    <item name="android:textColor">@color/orange</item>
    <item name="android:paddingTop">6dp</item>
    <item name="android:paddingBottom">6dp</item>
    <item name="android:layout_margin">2dp</item>
</style>

<style name="activeButtonTheme" parent="@style/buttonTheme">
    <item name="android:background">@color/orange</item>
    <item name="android:textColor">@color/white</item>
</style>

这里有什么问题?

我不想在 Java 中设置背景颜色,我只想在 Java 中更改样式。

【问题讨论】:

  • 确保您的 java 代码中不存在对 setBackground 的调用。
  • @AdamArold 除了这个和alertDialog之外什么都没有。

标签: java android styles android-styles


【解决方案1】:

为此目的使用selector。检查this link 了解详细信息(自定义背景部分)关于您的代码,在您的资源目录中定义适当的 selector.xml 文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/drawable_for_dissabled_button" android:state_enabled="false"/>
    <item android:drawable="@drawable/drawable_for_pressed_button" android:state_enabled="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true" android:state_focused="true"/>
    <item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true"/>
</selector>

将刚刚创建的选择器分配给布局文件中的按钮:

<Button android:id="@+id/your_button_id"
    android:background="@drawable/selector" />

【讨论】:

  • 谢谢!这行得通。你能说一下为什么我尝试的方法不起作用吗? background 属性有什么特别之处吗?
  • 据我所知,不支持在创建视图后更改样式。
  • 这不能解释为什么文本颜色会改变;这就是这一切的奇怪之处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 2018-12-25
  • 1970-01-01
相关资源
最近更新 更多