我为一个按钮提供了两个drawables xml文件。 在布局文件中,我设置为第一个xml。 这是我在drawable文件夹(setup.xml)中的第一个可绘制的xml: -
<item
android:state_pressed="true" >
<shape>
<corners android:radius="10dp" />
<solid android:color="#406934"></solid>
</shape>
</item>
<item
android:state_focused="true" >
<shape>
<corners android:radius="10dp" />
<solid android:color="#406934"></solid>
</shape>
</item>
我在我的布局文件中使用它: -
<Button
android:id="@+id/b_actionButton"
android:text="@string/page_button_action_text"
-------------
android:background="@drawable/setup"
style="@style/action_button" />
现在在运行时,我想根据某些条件将drawable更改为另一个xml(active_button.xml)文件。
我正在使用以下代码,但它们没有变化。
if (item.getTitle().equals("Stop ")) {
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.selectDrawable(R.drawable.active_button);
}
任何帮助或指示!!!
答案 0 :(得分:1)
由Sir先生提供,ρяσѕρєяK
请使用匹配,而不是等于
if (item.getTitle().matches("Stop"))
{
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.setBackgroundResource(R.drawable.active_button);
}
答案 1 :(得分:0)
假设@ drawable / setup_alert_button和setup.xml实际上是同一件事你的setup.xml需要一个没有和状态的项目(android:state_pressed =&#34; true&#34; / android:state_focused =&#34; true& #34;等)
该默认项应该是最后一项(drawable中的底部项)。它将用作默认状态,然后state_enabled和state_pressed应包含您的活动drawable。没有必要在代码中做任何事情。
如果您真的需要根据标题进行操作,请使用
holder.bActionButton.setBackgroundResource(R.drawable.active_button);