简体   繁体   中英

Button looses focus when touched outside

I have a button as an itemview in recyclerview which has both background and text selectors.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/channel"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/channel_bg"
android:focusableInTouchMode="true"
android:gravity="center"
android:textColor="@color/channel_text_selector"
android:textSize="12sp" />

Here is my @drawable/channel_bg

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/colorPrimary" />
        <corners android:radius="18dp" />
    </shape>
</item>
<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/colorPrimary" />
        <corners android:radius="18dp" />
    </shape>
</item>
<item>
    <shape android:shape="rectangle">
        <stroke android:width="1dp" android:color="@color/colorPrimary" />
        <solid android:color="@android:color/white" />
        <corners android:radius="18dp" />
    </shape>
</item>

Here is my @color/channel_text_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/white" android:state_pressed="true" />
<item android:color="@android:color/white" android:state_selected="true" />
<item android:color="@android:color/white" android:state_focused="true" />
<item android:color="@color/colorPrimary" />

When I touch/click on any other view on the same screen, button looses it's focus and goes in unselected state. Please help me on the same.

Your button loses focus as it's default behavior, if you don't touch it it's not focused. If you want your button to be focused after you click on other views you should request focus programmatically like this in OnFocusChangeListener

 btn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            btn.requestFocus();
        }
    });

So when the button gets "unfocused" the focus will be still requested but there's a caveat. You'll need to remove it when you need it too. Or it'll get stuck focused.

button.clearFocus();

You should also keep a boolean variable (as it was suggested in the comments) and then in case your recycler gets re-drawn check the boolean value and request focus or remove it later if you like

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM