Use group in ConstraintLayout to listen for click events on multiple views

前端 未结 6 1336
时光取名叫无心
时光取名叫无心 2020-12-24 11:48

Basically I\'d like to attach a single OnClickListener to multiple views inside a ConstraintLayout.

Before migrating to the ConstraintLayout the views where inside o

6条回答
  •  醉梦人生
    2020-12-24 12:13

    While I like the general approach in Vitthalk's answer I think it has one major drawback and two minor ones.

    1. It does not account for dynamic position changes of the single views

    2. It may register clicks for views that are not part of the group

    3. It is not a generic solution to this rather common problem

    While I'm not sure about a solution to the second point, there clearly are quite easy ones to the first and third.


    1. Accounting position changes of element in the group

    This is actually rather simple. One can use the toolset of the constraint layout to adjust the edges of the transparent view. We simply use Barriers to receive the leftmost, rightmost etc. positions of any View in the group. Then we can adjust the transparent view to the barriers instead of concrete views.

    3. Generic solution

    Using Kotlin we can extend the Group-Class to include a method that adds a ClickListener onto a View as described above. This method simply adds the Barriers to the layout paying attention to every child of the group, the transparent view that is aligned to the barriers and registers the ClickListener to the latter one.

    This way we simply need to call the method on the Group and do not need to add the views to the layout manually everytime we need this behaviour.

提交回复
热议问题