Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android button setPressed after onClick

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.

like image 458
strem Avatar asked May 12 '11 08:05

strem


2 Answers

Better solution:

In xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_activated="true">
        <bitmap android:src="@drawable/image_selected"/>
    </item>
    <item>
        <bitmap android:src="@drawable/image_not_selected"/>
    </item>
</selector>

And in java:

@Override
public void onClick(View v) {
   v.setActivated(!v.isActivated());
}
like image 55
M. Usman Khan Avatar answered Oct 05 '22 05:10

M. Usman Khan


Just to note this is because Android is changing the setPressed both before and after your onClickEvent, so changing it yourself has no effect. Another way to get around this is to use the onTouchEvent.

button.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        // show interest in events resulting from ACTION_DOWN
        if (event.getAction() == MotionEvent.ACTION_DOWN) return true;

        // don't handle event unless its ACTION_UP so "doSomething()" only runs once.
        if (event.getAction() != MotionEvent.ACTION_UP) return false;

        doSomething();
        button.setPressed(true);                    
        return true;
   }
});
like image 43
Martin Sykes Avatar answered Oct 05 '22 06:10

Martin Sykes