当您按下Android中的按钮时,它会改变颜色。我希望它保持这样。我的意思是我想要这样的东西:
Button btn = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn.setBackGroundColor(R.drawable.clicked /*clicked style*/ );
}
});
示例:
这是一个按下按钮。我希望它在我停止按下之后保持这种状态。有这样简单的方法:
android.R.drawable.btn_default //这是默认的按钮样式,我想要按下的样式:D
答案 0 :(得分:1)
在你的java代码中写button.setPressed(true);
。它会在按下的模式下设置按钮。如果要将其设置为按下和未按下,可以将参数更改为true和false ...
答案 1 :(得分:1)
所以你想让它开始非按下,然后点击一下后保持按下状态?
尝试使用OnTouchListener而不是添加btn.setPressed(true);
:
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
btn.setPressed(true);
}
return true;
}
答案 2 :(得分:1)
尝试使用选择器:
在drawable文件夹中定义selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="@drawable/button_normal_green" />
</selector>
并将按钮的背景设置为android:background="@drawable/selector"
然后在按钮集btn.setpressed(true);
的点击事件的代码中设置
答案 3 :(得分:0)
您可以尝试这种方式将图像按下时按下或颜色
抽拉/ selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_focused="true" android:drawable="@drawable/buttondark"/>
<item android:state_pressed="true" android:drawable="@drawable/buttondark" />
<item android:drawable="@drawable/button" />
</selector>
在on-create方法中编写
btn.setBackgroundResource(R.drawable.selector);
答案 4 :(得分:0)
看看StateSelector图像
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
您可以为按钮/视图的不同状态设置不同的资源。此示例设置不同的颜色:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@color/branded_content_background_color"/>
</selector>
然后你可以正常设置选择器
button.setBackgroundResource(R.drawable.selector);