Question

I developed one apps in that one i used view pager using fragment.In that i move to one page to another using fragment class.in second fragment class i have one button back on that i write coding to move direct to first fragment through fragment.replace but after replacing first fragment i don't scroll pager page to one to another means when i click on back button i move to first fragment but i not able to go back to that class againg. So i can not have idea to hove move/scroll page again to go first to second fragment. please help me quickly,thanks in advance.

My First class follewing :

enter code here
         public class ViewPagerMainActivity extends FragmentActivity implements
    OnClickListener, OnPageChangeListener {

   // all variable declare here
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    );

    setTheme(android.R.style.Theme_Light_NoTitleBar);


    setContentView(R.layout.view_pager_main);
    // other code here

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(
            android.support.v4.app.FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int pos) {
        switch (pos) {

        case 0:
            return FirstFragment.newInstance("");

        case 1:
            return SecondFragment.newInstance("");

        default:
            return SecondFragment.newInstance("Default");
        }
    }

    @Override
    public int getCount() {
        return 2; // return no of fragment created by us
    }
}

@Override
public void onClick(View v) {

}

@Override
public void onPageScrollStateChanged(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
    // TODO Auto-generated method stub

}

@Override
public void onPageSelected(int arg0) {
    // TODO Auto-generated method stub

}
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
}

}

enter code here  SECOND FILE
           public class FirstFragment extends Fragment implements OnTouchListener {

      // all variable decalre here
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    getActivity().setTheme(android.R.style.Theme_Light_NoTitleBar);
    v = inflater.inflate(R.layout.sliding_lock_pager, container, false);

    // other code here
    return v;
}

public static FirstFragment newInstance(String text) {

    FirstFragment f = new FirstFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);
    f.setArguments(b);

    return f;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    return false;
}

} third file enter code here public class SecondFragment extends Fragment implements OnClickListener {

// all varible decalare here
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    getActivity().setTheme(android.R.style.Theme_Light_NoTitleBar);
    View v = inflater.inflate(R.layout.password, container, false);

    // other code here
    // this method move to main pager 
    txtBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            final android.support.v4.app.FragmentTransaction ft = getFragmentManager()
                    .beginTransaction();

                ft.replace(R.id.layputMainPager, new FirstFragment(),
                        "NewFragmentTag");
                ft.addToBackStack(null);
                ft.commit();
        }
    });

    return v;
}

public static SecondFragment newInstance(String text) {

    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);
    f.setArguments(b);
    return f;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

   See in secondFragment class when i back through back button then i want to scroll again to that page i not do that. i move again to that page though page scroll. and in ft.replace(R.id.layputMainPager, new FirstFragment()) R.id.layputMainPager is  `class ViewPagerMainActivity` class xml files a

main layout id.

Was it helpful?

Solution

I have gone through same problem few days back, I think you are mixing 2 different implementations:

  1. If you are using fragments with ViewPager. You can use ViewPager's setCurrentItem() method to move to next or prev fragment.

  2. If you use only fragments then to move between fragments you can to use FragmentTransaction class methods like replace(), add() etc.

Hope this will clear things. Please share code if something is still unclear.

EDIT

You can overload onBackPressed() method something like :

@Override
public void onBackPressed() {
    // you can also check for current viewpager item by 
    // mViewpager.getCurrentItem()  
     mViewPager.setCurrentItem(precFragment, true);

}

If you are added Button in your fragment you can do something like :

Button back =  (Button) rootView.findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((YourActivity)getActivity()).mViewPager.setCurrentItem(prevFragment);

        }
    });

Edit : Added Code

  public class MainActivity extends Activity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
 * derivative, which will keep every loaded fragment in memory. If this
 * becomes too memory intensive, it may be best to switch to a
 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onBackPressed() {

     mViewPager.setCurrentItem(0, true);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return new FirstFragment();
        case 1:
            return new SecondFragment();
        default:
            break;
        }
        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        }
        return null;
    }
}

 }

FirstFragment File

  public class FirstFragment extends Fragment {
/**
 * The fragment argument representing the section number for this
 * fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static FirstFragment newInstance(int sectionNumber) {
    FirstFragment fragment = new FirstFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

public FirstFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container,
            false);
    Button next =  (Button) rootView.findViewById(R.id.button1);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ((MainActivity)getActivity()).mViewPager.setCurrentItem(1);

        }
    });
    return rootView;
}
}

SecondFragment File

 public class SecondFragment extends Fragment {
/**
 * The fragment argument representing the section number for this
 * fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static SecondFragment newInstance(int sectionNumber) {
    SecondFragment fragment = new SecondFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

public SecondFragment() {
}

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

    Button back =  (Button) rootView.findViewById(R.id.button1);
    back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ((MainActivity)getActivity()).mViewPager.setCurrentItem(0);

        }
    });
    return rootView;
}
 }

Please see the onBackPressed() Method and back.setOnClickListener() in SecondFragment file. Hope this will help

OTHER TIPS

There are a better implementation with the interfaces.

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    Button next = (Button) rootView.findViewById(R.id.button1);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).mViewPager.setCurrentItem(1);

        }
    });
    return rootView;
}

should replaced by that: Fragment file

public class FirstFragment extends Fragment {

private static final String ARG_SECTION_NUMBER = "section_number";

private OnSetCurrentItemListener mListener;
private int mSection;

public interface OnSetCurrentItemListener {
    void onGotoItem(int position);
}


public static FirstFragment newInstance(int sectionNumber) {
    FirstFragment fragment = new FirstFragment();
    Bundle args = new Bundle();

    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}


// This method pass a listener to the activity through Fragment LifeCycle creation.
// No needs to cast you Activity cause the method bring it; 
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnSetCurrentItemListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " needs to implement OnSetCurrentItemListener");
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getArguments();
    mSection = extras.getInt(ARG_SECTION_NUMBER);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first, container, false);
    Button next = (Button) rootView.findViewById(R.id.button1);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int target = mSection + 1;
            target = (target < 0) ? 0 : target; //checks bounds
            //to go next
            mListener.onGotoItem(mSection + 1);
            //to prev
            //mListener.onGotoItem(mSection - 1);
        }
    });
    return rootView;
}
}

On your acitivity File:

public class ViewPagerMainActivity extends FragmentActivity implements OnSetCurrentItemListener {

...

@Override
public void onGotoItem(int position) {
    mViewPager.setCurrentItem(position);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top