Search code examples
androidandroid-layoutandroid-fragmentsandroid-viewpageronclicklistener

OnClick Listener is not triggered inside a fragment with View Pager


I'd like to be able to set a View.OnclickListener to an ImageView inside a page (fragment) of my ViewPager, I don't want to click on the whole page of my ViewPager, I just want to be able to click on a specifig ImageView. I followed these questions (onClick not triggered on LinearLayout with child, How to set OnClickListener in ViewPager ) but they did not help me. This is my actual code:

MyPageFragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="240dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:focusableInTouchMode="true"
        android:id="@+id/container_linear"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop" />
    </LinearLayout>

</LinearLayout>

MyActivity.xml

<android.support.v4.view.ViewPager
                    android:id="@+id/product_view_pager"
                    android:layout_width="match_parent"
                    android:layout_height="240dp"
                    android:layout_marginLeft="4dp"
                    android:layout_marginRight="4dp"
                    android:gravity="center"
                    android:overScrollMode="never" />

MyFragment.class (where I'm binding the views using Butterknife)

@BindView(R.id.container_linear)
LinearLayout mContainer;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View mRootView = inflater.inflate(R.layout.my_layout, container, false);
    ButterKnife.bind(this, mRootView);

    mContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Test", "Clicked!");
        }
    });
}

Thanks for your support.


Solution

  • I solved this issue using the following chunk of code:

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
    
        view.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
    
                /*  Do as you please here. */
            }
        });
    }
    

    The reference for this answer can be viewed here: How to detect click on ImageView in ViewPager's PagerAdapter (android)?