开发者

Set button state programmatically

开发者 https://www.devze.com 2023-04-09 15:09 出处:网络
I define my button\'s states with <?xml version=\"1.0\" encoding=\"utf-8\"?> <selector xmlns:android=\"http://schemas.android.com/apk/res/android\">

I define my button's states with

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" >
        <shape>
            <gradient
                android:endColor="@color/orange_light"
                android:startColor="@color/orange"
                android:angle="270" />            
            <corners
                android:radius="6dp" />
            <padding
                android:left="10dp"                
                android:right="10dp" />
        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                android:endColor="@color/orange_light"
                android:startColor="@color/orange"
                android:angle="270" />
            <corners
                android:radius="6dp" />
            <padding
                android:left="10dp"                
                android:right="10dp" />
        </shape>
    </item>

    <item>        
        <shape>
            <gradient
                android:endColor="@color/grey_light"
                android:startColor="@color/grey"
          开发者_如何学Python      android:angle="270" />
            <corners
                android:radius="6dp" />
            <padding
                android:left="10dp"
                android:right="10dp" />
        </shape>
    </item>
</selector>

and set this as my button's background.

When I press it it change colors properly, but I'd like it to keep the 'pressed' color once released (to show which button is active).

How can I do this? requestFocus() does not work...

Thanks


well in your setOnClickListener you can implement some logic. For example ones the button is pressed it get one color and keeps that color until other button is pressed and when the second one i pressed than the first button's background gets reset to default....

you can implement what ever you want you just need to add some logic and that it is. If you want your button to have some color just for the time is in pressed state than override the on touch listener

you can do like this

addButtonLayout.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
        imageAddSign.setImageResource(R.drawable.a);
        }else{
        imageAddSign.setImageResource(R.drawable.b);
        }
        return false;
    }
});


I think, what you need is a checkbox and not a button. Try to set the background there or subclass it if you need more features.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号