![](/img/trans.png)
[英]How to change the background color of an icon in the action bar, when clicked?
[英]how to change button background color as clicked action?
-在android应用程序中-
单击按钮后,其背景色更改为必填。 再次单击,其颜色将恢复原始颜色。
如何执行呢?
任何回应,谢谢!
================================================== ================================更新:从网络上,我找到了一种实现这一目标的方法。 在xml中设计可绘制颜色,如下所示:
<drawable name="button_checked">#ffff0000</drawable>
在活动中,使用以下代码获取Drawable对象:
Resources resource = getBaseContext().getResources();
checked_drawable = resource.getDrawable(R.drawable.button_checked);
在onClick函数中,根据布尔变量:
setBackgroundDrawable(checked_mDrawable)
设置按钮背景。
在你的js文件中
$('#button')。toggleClass('bg');
在您的CSS中,使用常规的按钮CSS样式
#button { background: white; }
然后添加
#button.bg { background: red; }
因此,当他们单击按钮时,它将变成红色的背景,如果再次单击它,它将变成白色。
使用任何想要的背景颜色/网址。
您只需要创建一个状态列表可绘制资源,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_login_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_login_normal" android:state_pressed="false"/>
</selector>
更新:也许您希望将效果用作RadioButton,这是一个示例:
<RadioButton
android:id="@+id/tab_communication"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@null"
android:button="@null"
android:drawableTop="@drawable/category_communication"
android:paddingBottom="5dp"
android:paddingTop="5dp" />
drawable / category_communication.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/category_communication_checked" android:state_checked="true"/>
<item android:drawable="@drawable/category_communication_normal" android:state_checked="false"/>
</selector>
ToggleButton是另一个选择。
您可以在代码中动态地做到这一点(我不知道如何在xml中配置它)。
boolean flag=true;
Button button=(Button)findViewById(R.id.button);
oncreate()
{
button.setBackgroundResource(R.drawable.first_time_click);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (flag)
{
button.setBackgroundResource(R.drawable.odd_time_click);
}else
{
button.setBackgroundResource(R.drawable.even_time_click);
}
flag=!flag;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.