confidante confidante - 5 months ago 35
Android Question

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.

this Image is for understanding

this is my xml file for my cardview








<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/chapter_number"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:background="@color/notes_chapternumber_background"
android:padding="5dp"

android:textAllCaps="true"
android:textColor="@color/notes_chapternumber_background_text"
android:textSize="25sp" />


<ImageView
android:id="@+id/chapter_photo"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/chapter_number"
android:padding="5dp" />


<TextView
android:id="@+id/chapter_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/chapter_number"
android:layout_margin="5dp"
android:layout_toRightOf="@+id/chapter_photo"
android:gravity="center_vertical"
android:textColor="#080300"
android:textSize="20sp" />

<ImageButton
android:id="@+id/chapter_description"
android:layout_width="36dp"
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"/>


</RelativeLayout>







This is my MainActivity file




public class NotesActivty extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
int currentSelectedTab = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Notes");
toolbar.setSubtitle("Pattern of IIB");
setSupportActionBar(toolbar);


mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

mViewPager = (ViewPager) findViewById(R.id.container);

mViewPager.setAdapter(mSectionsPagerAdapter);

SmartTabLayout tabLayout = (SmartTabLayout) findViewById(R.id.tabs);

tabLayout.setViewPager(mViewPager);



}


public class SectionsPagerAdapter extends FragmentPagerAdapter {

public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
if (position == 0) {
return new NotesFragment11th();
} else if (position == 1) {
return new NotesFragment12th();
} else if (position == 2) {
return new NotesFragmentExams();
}

return null;
}

@Override
public int getCount() {

return 3;
}


@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "11th";
case 1:
return "12th";
case 2:
return "Exams";
}
return null;
}
}


}




And this is my adapter file



public class NotesChapterAdapter extends RecyclerView.Adapter {

public static class ChapterViewHolder extends RecyclerView.ViewHolder {

CardView cv;
TextView chapterNumber;
TextView chapterName;
ImageView chapterPhoto;

ChapterViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.notes_card_view);
chapterNumber = (TextView) itemView.findViewById(R.id.chapter_number);
chapterName = (TextView) itemView.findViewById(R.id.chapter_name);
chapterPhoto = (ImageView) itemView.findViewById(R.id.chapter_photo);

}
}

List<Chapter> chapters;

public NotesChapterAdapter(List<Chapter> chapters) {
this.chapters = chapters;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}

@Override
public ChapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notes_cardview, viewGroup, false);
ChapterViewHolder pvh = new ChapterViewHolder(v);
return pvh;
}

@Override
public void onBindViewHolder(NotesChapterAdapter.ChapterViewHolder holder, int position) {
holder.chapterNumber.setText(chapters.get(position).number);
holder.chapterName.setText(chapters.get(position).name);
holder.chapterPhoto.setImageResource(chapters.get(position).chapterPhoto);
holder.imageButton.setTag(position);
}


@Override
public int getItemCount() {
return chapters.size();
}


}




And this is my one one of three Fragment class which are same




public class NotesFragmentExams extends Fragment {
private List<Chapter> chapters;
RecyclerView recList;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.notes_fragment_chapter, container, false);

recList = (RecyclerView) view.findViewById(R.id.cardList);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
initializeData();
initializeAdapter();


return view;


}


private void initializeData() {
chapters = new ArrayList<>();

chapters.add(new Chapter("Chapter 1", "Diversity in organisms", R.drawable.image0));
chapters.add(new Chapter("Chapter 2", "Kingdom Plantae", R.drawable.image1));
chapters.add(new Chapter("Chapter 3", "Biochemistry of cell", R.drawable.image2));

}

private void initializeAdapter() {
NotesChapterAdapter adapter = new NotesChapterAdapter(chapters);
recList.setAdapter(adapter);
}
}





Please help me out with this.

ITS FINALLY SOLVED.

Updated OnClick for Imageview.

public void onMyClick(View v) {
int position = (int) v.getTag();

if (selectedTab == 0) {
if (position == 0) {
Toast.makeText(this, "Position 1", Toast.LENGTH_LONG).show();

} else if (position == 1) {
Toast.makeText(this, "Position 2", Toast.LENGTH_LONG).show();

} else if (position == 2) {
Toast.makeText(this, "Position 3", Toast.LENGTH_LONG).show();

} else if (position == 3) {
Toast.makeText(this, "Position 4", Toast.LENGTH_LONG).show();

} else if (position == 4) {
Toast.makeText(this, "Position 5", Toast.LENGTH_LONG).show();

} else if (position == 5) {
Toast.makeText(this, "Position 6", Toast.LENGTH_LONG).show();

}

} else if (selectedTab == 1) {
if (position == 0) {
Toast.makeText(this, "Position 1", Toast.LENGTH_LONG).show();

} else if (position == 1) {
Toast.makeText(this, "Position 2", Toast.LENGTH_LONG).show();

} else if (position == 2) {
Toast.makeText(this, "Position 3", Toast.LENGTH_LONG).show();

} else if (position == 3) {
Toast.makeText(this, "Position 4", Toast.LENGTH_LONG).show();

} else if (position == 4) {
Toast.makeText(this, "Position 5", Toast.LENGTH_LONG).show();

} else if (position == 5) {
Toast.makeText(this, "Position 6", Toast.LENGTH_LONG).show();

}
} else {
if (position == 0) {
Toast.makeText(this, "Position 1", Toast.LENGTH_LONG).show();

} else if (position == 1) {
Toast.makeText(this, "Position 2", Toast.LENGTH_LONG).show();

} else if (position == 2) {
Toast.makeText(this, "Position 3", Toast.LENGTH_LONG).show();

}
}

}

Answer

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"/>
Comments