Nodir Rashidov
Nodir Rashidov

Reputation: 732

onclicklistener on a viewgroup with its child views

I have a relative layout that I want to make tappable, including its child views.

<RelativeLayout
    android:id="@+id/houses_rel_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:background="@drawable/white_grey_border_bottom">

    <HorizontalScrollView
        android:id="@+id/houses_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:duplicateParentState="true"
        android:scrollbars="none">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            ...
        </LinearLayout>
    </HorizontalScrollView>

    <TextView... />
    .....
</RelativeLayout>

layout

I want to set an onclicklistener on the relative layout, the horizontal view, and the textviews, and a separate onclicklistener on the icon.

@BindView(R.id.houses_rel_1)
ViewGroup mHouse;

@BindView(R.id.fav_icn_1)
ImageView mFavIcn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_house_list);
    ButterKnife.bind(this);

    mHouse.setOnClickListener(new ViewGroup.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(mContext, SomeActivity.class);
            mContext.startActivity(intent);
        }
    });
    mFavIcn.setOnClickListener(new View.OnClickListener() {
        ...
    });
}

Currently, the new activity is staring only when I tap on the textviews, but nothing happens when I tap on the horizontalscrollview. Do I have to duplicate the onclicklistener to horizontalscrollview?

Upvotes: 1

Views: 1759

Answers (2)

Relish Wang
Relish Wang

Reputation: 385

Please use setOnTouchListener() on horizontalScrollView instead of setOnClickListener().

Mmmmmm...The reason is very complicated. After I read the source code of HorizontalScrollView.java, I found it overrides these methods of View or ViewGroup--onTouchEvent, onInterceptTouchEvent.Without use super.onTouchEvent,super.onInterceptTouchEvent.It partly means if you set a OnClickListener on it(HorizontalScrollView), the onClick event will never be invoked.

If you want to know more about, you can read the source code too. It will more helpful then I telling you the reason, cuz I may have some misinterpretations in reading.

I hope that helps you.

Upvotes: 1

Addell El-haddad
Addell El-haddad

Reputation: 163

Try grouped onClick of Butter Knife :

@OnClick({ R.id.houses_1, R.id.houses_rel_1 })
public void startSomeActivity() {
   Intent intent = new Intent(mContext, SomeActivity.class);
        mContext.startActivity(intent);
}

Upvotes: 1

Related Questions