Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-recyclerviewcardview

How to use same button with different functionality in different Fragments using same layout file in TabActivity


I have a question from last few days. I basically have three fragments in a TabActivity, Fragment A, Fragment B and Fragment C. All three Fragments contain a list of CardView of approximately 14 CardViews in single Fragment. This three Fragment share same layouts with same cardview with same id. There is a button in each CardView and i want to start different activity's when clicked on that button. But I cant do it because id for button is same and I want to start activity's when that button is clicked from different Fragments. I am using RecyclerView for this. It means I have 14 buttons in a Fragment and there are three Fragments.


Solution

  • If the button is in recyclerView, you can set a click listener of that button in XML, which will be called in Your Activity. Now your recyclerView adapter , set a tag which will be the position of the cell to you your button.

    holder.imageButton.setTag(position);
    

    Now, in your main activity, create an integer variable named

    int currentSelectedTab = 0;
    

    and then do this on your TabChange listener.;

     mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                selectedTab = position;
            }
    
            @Override
            public void onPageSelected(int position) {
    
            }
    
            @Override
            public void onPageScrollStateChanged(int state) {
    
            }
        });
    

    Now you will always have the current selected tabPosition.

    And in clicklistener in your Activity do this ::

      public void myOnClick(View v) {
    
    if(current selectedTab == 1)
    {
    
    if(v.getId === R.id.btn1)
    {
    
    // it means btn of Fragment 1 is clicked
    // same goes for other button clicks
    // and for the index of button
    // v.getTag() it will you which cell's button was clicked
    
     }
    

    In your cardView xml :

     <ImageButton
        android:id="@+id/chapter_description"
        android:layout_width="36dp"
        android:onClick="myOnClick"
        android:layout_height="36dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/description"
        android:background="@drawable/ripple_effect"/>