如何在viewPager中使用相同的片段?

时间:2014-03-28 09:39:27

标签: android android-fragments replace android-viewpager android-pageradapter

我开发了一个带有片段和viewPager的小样本应用程序。 viewPager显示3页。在每个页面中,我实例化相同类型的片段。该片段包含textView和一个按钮。在按钮单击时,我想用另一个片段替换当前片段。现在我的问题是,无论我按哪个按钮,只有第1页的片段被替换。我不知道我在pageAdapter类中要做什么,但我想这与使用相同的片段和布局有关。我想我必须确保我的pageAdapter更新了正确的页面,但我该如何实现呢?

为了更好地理解为什么我要实现这一点,我在类型菜单的3个节点中收到一个json字符串,我想将它们中的每一个用作我的viewPager中的页面。

有人能告诉我这种行为的简短例子吗?我认为这是一种基本方法,所以它不会那么困难。

-------- ---------编辑

以下是代码:

public class FragmentPagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;

@Override
public void onBackPressed() {
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        fm.popBackStack();
    } else {
        super.onBackPressed();
    }
}

public MyAdapter getmAdapter() {
    return mAdapter;
}

public ViewPager getmPager() {
    return mPager;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_pager);
    mAdapter = new MyAdapter(getFragmentManager(), this);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPager.setOffscreenPageLimit(NUM_ITEMS + 2);
    mPager.setAdapter(mAdapter);

    Button button = (Button) findViewById(R.id.goto_first);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPager.setCurrentItem(0);
        }
    });

    button = (Button) findViewById(R.id.goto_last);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPager.setCurrentItem(NUM_ITEMS - 1);
        }
    });
}
}

MyAdapter:

public MyAdapter(FragmentManager fm, FragmentPagerSupport fragmentPagerSupport) {
super(fm);
this.fragmentPagerSupport = fragmentPagerSupport;
}

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

@Override
public Fragment getItem(int position) {
        Fragment newInstance = null;
        switch (position) {
        case 0:
            newInstance = frag1.newInstance(position);
            break;
        case 1:
            newInstance = frag1.newInstance(position);
            break;
        case 2:
            newInstance = frag2.newInstance(position);
            break;
        case 3:
            newInstance = frag2.newInstance(position);
            break;
        }
        return newInstance;
    }

Frag1& Frag2& ListItemFrag:

    public static class frag1 extends ListFragment {
    int mNum;
    static frag1 newInstance(int num) {
        frag1 f = new frag1();
        Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        v.setId(mNum);
        View tv = v.findViewById(R.id.text);
        ((TextView) tv).setText("Fragment #" + mNum);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("FragmentList", "Item clicked: " + id);
        String itemName = (String) l.getItemAtPosition(position);
        Fragment listItemFragment = ListItemFragment.newInstance(itemName);
        FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
        trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
        trans.addToBackStack(itemName);
        trans.commit();
    }
}

public static class frag2 extends ListFragment {
    int mNum;
    static frag2 newInstance(int num) {
        frag2 f = new frag2();
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        v.setId(mNum);
        View tv = v.findViewById(R.id.text);
        ((TextView) tv).setText("Fragment #" + mNum);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("FragmentList", "Item clicked: " + id);
        String itemName = (String) l.getItemAtPosition(position);
        Fragment listItemFragment = ListItemFragment.newInstance(itemName);
        FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
        trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
        trans.addToBackStack(itemName);
        trans.commit();
    }
}

public static class ListItemFragment extends Fragment {
    String itemName;
    static ListItemFragment newInstance(String itemName) {
        ListItemFragment i = new ListItemFragment();
        Bundle args = new Bundle();
        args.putString("text", itemName);
        i.setArguments(args);
        return i;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemName = getArguments() != null ? getArguments().getString("text") : "NULL";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_item, container, false);
        View tv = v.findViewById(R.id.textView1);
        ((TextView) tv).setText("Cheese: " + itemName + " selected!");
        return v;
    }
}

寻呼机布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
        android:gravity="center" android:measureWithLargestChild="true"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0">
    <Button
        android:id="@+id/goto_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="first" />
    <Button android:id="@+id/goto_last"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="last">
    </Button>
</LinearLayout>

Frag1布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="@+id/test">
<TextView android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/hello_world"/>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:id="@+id/root" >
    <ListView android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawSelectorOnTop="false"/>
</FrameLayout>

Frag2布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="@+id/test2">
<TextView android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/hello_world"/>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:id="@+id/root2" >
    <ListView android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawSelectorOnTop="false"/>
</FrameLayout>

ListItemFrag布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="230dp"
android:background="#AA33EE"
android:orientation="vertical" >
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

1 个答案:

答案 0 :(得分:2)

您好我面临同样的问题。我使用

解决了这个问题
getChildFragmentManager().beginTransaction()

而不是

getActivity().getSupportFragmentManager().beginTransaction()

在这种情况下,我们试图从一个片段中进行事务处理(连接到ViewPager的片段列表中的一个,因此持有ViewPager的Activity)所以我们必须在这里使用getChildFragmentManager()结果

注意:我使用的是android支持v4库,因此对应的FragmentManager。