Avoid ImageView hover state inside Listview if List Item is pressed

好久不见. 提交于 2019-12-11 04:24:35

问题


I have a ImageView inside listview in left most position.This imageView and listView has all states (pressed ,selected,focused,normal).If I click ListView but not ImageView then in some devices the hover state(selected,focused,pressed) of ImageView is called. So I want to know how to avoid this.


回答1:


Here are the steps to resolve this issue. Create a class called NoParentPressImageView with the following code:

public class NoParentPressImageView extends ImageView {

    public NoParentPressImageView(Context context) {
        this(context, null);
        this.setFocusable(false);
    }

    public NoParentPressImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setFocusable(false);
    }

    @Override
    public void setPressed(boolean pressed) {
        // If the parent is pressed, do not set to pressed.
        if (pressed && ((View) getParent()).isPressed()) {
            return;
        }
        super.setPressed(pressed);
    }
}

Note that the setFocusable(false) in the constructor has the same effect as adding android:focusable="false" to the xml layout document. This allows the ListView rows to be clickable. The onPressed override method solves the problem that you mention here, namely press events in the ListView (parent) rippling through to the ImageView (child).

Once you have this class defined, you can replace ImageView in your xml layout with com.MYCOMPANY.MYAPP.NoParentPressImageView. Compile and run, and the ListView should now behave as you expect, with the ImageView pressed events only being triggered when you actually click on the image and not when you click elsewhere in the row.




回答2:


Try adding android:focusable="false" to the ImageView in your layout file.



来源:https://stackoverflow.com/questions/14869236/avoid-imageview-hover-state-inside-listview-if-list-item-is-pressed

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