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.
Implement on click listener in your activity. On each button click programatically do whatever changes you want to do in the layout..
Example below
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button1:
// Do something
break;
case R.id.button2:
// Do something
break;
case R.id.button3:
// Do something
}
}
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"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.