How can I keep a button as pressed after clicking on it? [duplicate]

拈花ヽ惹草 提交于 2019-12-17 09:19:17

问题


Possible Duplicate:
Android. How do I keep a button displayed as PRESSED until the action created by that button is finished?

I have a button, and I want that when I press it, it stays as pressed (with the green color on Froyo).

Any help?

mycodes_Button = (Button) findViewById(R.id.mycodes);
...
if (saved_Button.isPressed())
{
    saved_Button.setFocusable(true);
}

Something like this?


回答1:


Use the following code. It's useful.

mycodes_Button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mycodes_Button.setPressed(true);
        return true;
    }
});



回答2:


I had this issue with a button with a custom background, and ended up using the selected state for this. That state is available for all views.

To use this you have to define a custom button background as a state list:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_selected="false" android:state_focused="false" 
     android:state_pressed="false"><bitmap ... /></item>
  <item android:state_selected="true"><bitmap ... /></item>
  <item android:state_focused="true"><bitmap ... /></item>
  <item android:state_pressed="true"><bitmap ... /></item>
</selector>

Then to use that background, let's say it is in /res/drawable/button_bg.xml in your layout file, you use:

...
<Button android:background="@drawable/button_bg" ... />
...

In your code you can switch to the (de-)selected state in your onClick listener:

myButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    v.setSelected(true);
    // normal click action here
  }
});

The activated state matches the intended meaning better, but is only available from Android 3.x and higher.




回答3:


Would a ToggleButton suit your needs?

Judging from your comments it seems that you aren't aware of the Touch Mode.In this mode, which is the default for most of the things, there is no focus (which is what you are trying to achieve) and no selected items.

You could try to exit the touch mode programmatically, but I wouldn't recommend it. After a small period of getting used to it, the touch mode will give a much better experience to the users.



来源:https://stackoverflow.com/questions/4747311/how-can-i-keep-a-button-as-pressed-after-clicking-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!