Android:Fragment和ViewPager始终在第一个位置启动

时间:2014-01-13 21:36:27

标签: android listview android-fragments android-viewpager

我在Android应用程序中使用Master / Detail设计。如果我单击ItemListActivity中列表视图中的项目,则会将位置提供给我的ItemDetailActivity。这个实现了ViewPager和FragmentStatePagerAdapter。所以我想在细节视图之间滑动。

我不知道如何告诉ViewPager从所需位置开始(ItemListActivity中的整数)。无论我在列表中点击哪一个,我的ViewPager始终位于列表的第0位。

这是我的代码:

ItemDetailActivity

public class ItemDetailActivity extends FragmentActivity {

    RSSFeed feed;
    int pos;
    private static List<Fragment> fragments;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;


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

        // define layout of this activity
        setContentView(R.layout.activity_item_detail);

        // Get the feed object and the position from the Intent
        feed = (RSSFeed) getIntent().getExtras().get("feed");
        //position of the clicked item from the list
        pos = getIntent().getExtras().getInt("pos");

        //create all 20 ItemDetailFragments
        fragments = new ArrayList<Fragment>();
         for(int i=0; i<=20; i++)
                fragments.add(ItemDetailFragment.create(i ,feed));

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.viewpager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setPageTransformer(true, new ZoomOutPageTransformer());
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter that represents ItemDetailFragment objects, in
     * sequence.
     * 
     * Creates a class that extends the FragmentStatePagerAdapter abstract class and
     * implements the getItem() method to supply instances of ScreenSlidePageFragment
     * as new pages. The pager adapter also requires that you implement the getCount()
     * method, which returns the amount of pages the adapter will create. 
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

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

        @Override
        public Fragment getItem(int page_number) {
            return fragments.get(page_number);
        }

        @Override
        public int getCount() {
            //get the count of items in the feed
            return feed.getItemCount();
        }
    }

ItemDetailFragment:

/**
 * A fragment representing a single Item detail screen. This fragment is either
 * contained in a {@link ItemListActivity} in two-pane mode (on tablets) or a
 * {@link ItemDetailActivity} on handsets.
 */
public class ItemDetailFragment extends Fragment {

    private static int fPos;
    static RSSFeed fFeed;
    private ShareActionProvider mShareActionProvider;
    Date pDate;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemDetailFragment() {
    }

    /**
     * Factory method for this fragment class. Constructs a new fragment for the given page number.
     */
    public static ItemDetailFragment create(int pos, RSSFeed feed) {

        ItemDetailFragment fragment = new ItemDetailFragment();     
        Bundle args = new Bundle();
        args.putSerializable("feed", feed);
        args.putInt("pos", pos);
        fragment.setArguments(args);        
        return fragment;
    }

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

        // show ActionBar
        setHasOptionsMenu(true);

        // get data from DetailActivity
        fFeed = (RSSFeed) getArguments().getSerializable("feed");
        fPos = getArguments().getInt("pos");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // inflate the fragment with the custom detail fragment
        View view = inflater
                .inflate(R.layout.detail_fragment, container, false);

        return view;
    }
@SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
               //here I put the data in my webview
    }

activity_item_detail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/main_item_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <android.support.v4.view.ViewPager
     android:id="@+id/viewpager"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" />

    <FrameLayout
        android:id="@+id/item_detail_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/adView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        tools:context=".ItemDetailActivity"
        tools:ignore="MergeRootFrame" >

    </FrameLayout>

所以目前我可以对所有项目进行平局,但始终从第一项开始。我想在我列表视图中点击的那个项目上启动它。

我该怎么做?

2 个答案:

答案 0 :(得分:8)

根据文档,您需要做的就是使用

mPager.setCurrentItem(pos);

http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setCurrentItem(int)

答案 1 :(得分:2)

您实际上已经在onBackPressed()方法中使用了您需要使用的方法:

mPager.setCurrentItem(mPager.getCurrentItem() - 1);

只需传递Bundle中的初始位置,然后在设置时调用此方法。