Android: How to propagate click event to LinearLayout childs and change their drawable

五迷三道 提交于 2019-11-29 23:08:55

Put

android:duplicateParentState="true"

in your ImageView and TextView..then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.

Not only make for every child:

android:duplicateParentState="true"

But also additionally:

android:clickable="false"  

This will prevent unexpected behaviour (or solution simply not working) if clickable child views are used.

SO Source

Bernd

After having the same problem some months later, I found this solution:

private void setOnClickListeners() {
    super.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            onClick(v);
        }
    });
    for (int index = 0; index < super.getChildCount(); index++) {
        View view = super.getChildAt(index);
        view.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                onClick(v);
            }
        });
    }
}

protected void onClick(View v) {
    // something to do here...
}

In my case, no one of the other solutions works!

I finally had to use OnTouchListener as explained here, capturing the event when the user clicks in the parent view, and removing all childs OnClickListener.

So the idea is, delegate the click behavior to the parent, and notify the child that is really clicked, if you want to propagate the event. ¡¡That's what we are looking for!!

Then, we need to check which child has been clicked. You can find a reference here to know how it´s done. But the idea is basiclly getting the area of the child, and asking for who contains the clicked coordinates, to perform his action (or not).

At first, my child view failed to get click from parent. After investigating, what I need to do to make it work are:

  1. remove click listener on child view
  2. adding click listener on parent view

So, I don't need to add these on every children.

android:duplicateParentState="true"
android:clickable="false"

I only add duplicateParentState to one of my child view.

My child view is now listening to parent click event.

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