سؤال

I am learning how to use ViewPager in my android app. Right now, I was able to create a basic app with three tabs with swipe support. Now, what I'm thinking to do is, how can I go from one page to another using a button inside one of the fragments currently in the ViewPager, I have tried this one

Android ViewPager Prev/Next Button but it does not work for me, for a better understanding of what I am trying to achieve:

I have three(3) tabs (3 Fragments), TAB A, TAB B, TAB C

in TAB A, I have a button. I want the action of that button INSIDE TAB A(Fragment A) to go to TAB C (or TAB B). I've been searching for the right approach but to no avail. I hope someone can help me, Thanks!

هل كانت مفيدة؟

المحلول

okay here is how to add button in fragment A to switch fragment c : 1- add button in Fragment a in xml file which id foo like this :

<Button
    android:id="@+id/foo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="go to fragemnt c" />

go to fragment a class overide method called onCreateView and set onclickListner create by creating interface called it buttonClick and create var from it in side fragment a then override method onAttch initialize interface var inside onAttch method:

public class FragmentA extends Fragment {

buttonClick click;
Button foo;

interface buttonClick {
    void buttonClicked(View v);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    click = (buttonClick) activity;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_a, container,false);

    foo = (Button) view.findViewById(R.id.foo);
    foo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            click.buttonClicked(v);
        }
    });

    return view;
}

}

then back to your MainActivity implements buttonClick interface and override methods in the method called buttonClicked(View v); setCurrentItem for view pager like this :

calss MainActivity implements FragmentA.buttonClick {

   // your code here ...

   public void buttonClicked(View v){
      //get your viewPager var
      viewPager.setCurrentItem(3);
    }

}

i hope this helps

نصائح أخرى

Get your ViewPager, use

ViewPager.setCurrentItem(int item)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top