如何在运行时为按钮使用 drawable xml
how to use a drawable xml at runtime for a button
我为一个按钮准备了两个可绘制对象 xml 文件。
在布局文件中,我设置为第一个 xml。
这是我在 drawable 文件夹 (setup.xml) 中的第一个 drawable 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" />
现在在运行时,我想根据某些条件将可绘制对象更改为另一个 xml(active_button.xml) 文件。
我正在使用以下代码,但它们没有变化。
if (item.getTitle().equals("Stop ")) {
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.selectDrawable(R.drawable.active_button);
}
任何帮助或指点!!!
致谢 ρяσѕρєя K 先生
请使用匹配而不是等于
if (item.getTitle().matches("Stop"))
{
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.setBackgroundResource(R.drawable.active_button);
}
假设@drawable/setup_alert_button 和 setup.xml 实际上是同一件事,您的 setup.xml 需要一个不带状态的项目 (android:state_pressed="true" / android:state_focused="true", 等等)
该默认项应该是最后一项(drawable 中最底部的一项)。它将用作默认状态,然后 state_enabled 和 state_pressed 应该包含您的活动可绘制对象。无需在代码中执行任何操作。
如果您确实需要根据标题进行操作,请使用
holder.bActionButton.setBackgroundResource(R.drawable.active_button);
我为一个按钮准备了两个可绘制对象 xml 文件。 在布局文件中,我设置为第一个 xml。 这是我在 drawable 文件夹 (setup.xml) 中的第一个 drawable 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" />
现在在运行时,我想根据某些条件将可绘制对象更改为另一个 xml(active_button.xml) 文件。
我正在使用以下代码,但它们没有变化。
if (item.getTitle().equals("Stop ")) {
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.selectDrawable(R.drawable.active_button);
}
任何帮助或指点!!!
致谢 ρяσѕρєя K 先生
请使用匹配而不是等于
if (item.getTitle().matches("Stop"))
{
StateListDrawable background = (StateListDrawable) holder.bActionButton.getBackground();
background.setBackgroundResource(R.drawable.active_button);
}
假设@drawable/setup_alert_button 和 setup.xml 实际上是同一件事,您的 setup.xml 需要一个不带状态的项目 (android:state_pressed="true" / android:state_focused="true", 等等)
该默认项应该是最后一项(drawable 中最底部的一项)。它将用作默认状态,然后 state_enabled 和 state_pressed 应该包含您的活动可绘制对象。无需在代码中执行任何操作。
如果您确实需要根据标题进行操作,请使用
holder.bActionButton.setBackgroundResource(R.drawable.active_button);