android 按钮 setPressed 在 onClick 后
昨天我注意到可以通过兼容性包将片段集成到较旧的 API 级别中,但这对于这个问题来说并不是真正重要的。 :)
我有一个带有 OnClickListener 的按钮
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
doSomething();
button.setPressed(true);
}
});
由于实际单击,它显示为按下状态,释放单击后,按钮状态未按下并保持这种状态。
有没有一种简单的方法可以在释放按钮后保持按下状态? 我首先想到的是某种计时器,但这似乎不合理。
yesterday I noticed the possibility to integrate Fragments in older API Levels through the Compatibility package, but thats not really essential for the question. :)
I have a Button with an OnClickListener
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
doSomething();
button.setPressed(true);
}
});
Because of the actual clicking, it is shown as pressed and after releasing the click, the button state is not pressed and stays that way.
Is there a simple way that keeps the button state pressed after releasing?
First thing I can think of would be some sort of timer, but that seems unreasonable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是我使用的解决方案,目前它也适用于 android 7.0。
YourActivity.java
YourActivityLayout
values/styles.xml
drawable/generic_btn.xml
该选择器选择按钮背景。我使用按下作为激活。
颜色/selector_black_white
这里我设置了文字颜色。就我而言,我需要在按下时选择黑色文本颜色。
This is the solution I used, It also works on android 7.0 at the moment.
YourActivity.java
YourActivityLayout
values/styles.xml
drawable/generic_btn.xml
This selector chooses the button background. I use the pressed as the activated.
color/selector_black_white
Here I set the text color. In my case, I need to pick the textcolor black when pressed.
请注意,这是因为 Android 在
onClickEvent
之前和之后都更改了setPressed
,因此您自己更改它没有效果。解决这个问题的另一种方法是使用onTouchEvent
。Just to note this is because Android is changing the
setPressed
both before and after youronClickEvent
, so changing it yourself has no effect. Another way to get around this is to use theonTouchEvent
.使用
ToggleButton
而不是Button
。topping_selector.xml:
Use
ToggleButton
instead ofButton
.topping_selector.xml:
您可以将按钮状态保存在drawable文件夹下的xml文件中,然后用作按钮的背景。
例如:
buttonstate.xml
You can keep the button states in xml file under drawable folder, then used as background for button.
For example:
buttonstate.xml
更好的解决方案:
在 xml 文件中:
在 java 中:
Better solution:
In xml file:
And in java:
您可以使用 android.os.Handler 类。丑陋,但也有效:
You can use android.os.Handler class. Ugly, but works also:
另一种解决方案是扩展
Button
并重写setPressed(boolean Pressed)
方法,以便您可以使用标志处理来自onClickEvent
的平台调用,例如根据您的需要更改布尔按下参数。Another solution is to extend
Button
and overridesetPressed(boolean pressed)
method so you can handle platform calls from theonClickEvent
using a flag, for example changing the boolean pressed parameter depending on your needs.