在ViewPager中将片段替换为另一个片段

时间:2016-07-17 08:20:17

标签: android android-fragments android-viewpager android-fragmentactivity android-tablayout

当我尝试将一个片段替换为ViewPager中的另一个片段时,我遇到了一些问题。

  • 我有一个5页的ViewPager,每个页面都是一个片段。在第一页,我有一个recyclerview。当我点击该recyclerview的一个项目时,我使用addOnItemTouchListener方法处理该事件。
  • 单击recyclelerview项目时,我想将Fragment(categoryFragment)替换为另一个片段(" sub_category")。

CODE

ShopPanel活动(包含ViewPager和TabLayout)

ShopPanel.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.hyperfresh.sorooshpardaz.hyperfreshcustomer.ShopPanel">
<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:background="@drawable/toolbarshop">
</android.support.v7.widget.Toolbar>
<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>
<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/white"
    app:tabGravity="fill"/></LinearLayout>

ShopPanel.java

public class ShopPanel extends AppCompatActivity {

private TabLayout mTabLayout;

private int[] mTabsIcons = {
        R.drawable.menux,
        R.drawable.search,
        R.drawable.favorites,
        R.drawable.gift,
        R.drawable.home
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shop_panel);


    final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
    if (viewPager != null)
        viewPager.setAdapter(pagerAdapter);
    //  viewPager.setCurrentItem(pagerAdapter.PAGE_COUNT-2,false);
    mTabLayout = (TabLayout) findViewById(R.id.tab_layout);


    if (mTabLayout != null) {
        mTabLayout.setupWithViewPager(viewPager);

        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null)
                tab.setCustomView(pagerAdapter.getTabView(i));
        }

        mTabLayout.getTabAt(0).getCustomView().setSelected(true);
    }

    viewPager.post(new Runnable() {
        @Override
        public void run() {
            viewPager.setCurrentItem(0);

        }
    });

}
private class MyPagerAdapter extends FragmentPagerAdapter {

    public final int PAGE_COUNT = 5;

    private final String[] mTabsTitle = {"Menu","Search","Favorites","Gift","Home"};

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

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View view = LayoutInflater.from(ShopPanel.this).inflate(R.layout.custom_tab, null);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(mTabsTitle[position]);
        ImageView icon = (ImageView) view.findViewById(R.id.icon2);
        icon.setImageResource(mTabsIcons[position]);
        return view;
    }

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

            case 0:
                categoryFragment category = new categoryFragment();
                return category;
            case 1:
                searchFragment search = new searchFragment();
                return search;
            case 2:
                favoritesFragment favorites = new favoritesFragment();
                return favorites;
            case 3:
                giftFragment gift = new giftFragment();
                return gift;
            case 4:
                homeFragment home = new homeFragment();
                return home;
        }
        return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mTabsTitle[position];
    }


}}

categoryFragment First Fragment

public class categoryFragment extends Fragment {
private static final String REGISTER_URL = "http://torshiforoosh.ir/service/category.php";
List<categoryModel> categoryModelList;
AutofitRecyclerView re;
private final static String TAG = "categoryFragment";

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.category, container, false);
    re = (AutofitRecyclerView) view.findViewById(R.id.re);
    //StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
    //GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2);
    re.addItemDecoration(new MarginDecoration(getActivity()));
    re.setHasFixedSize(true);
    re.setItemAnimator(new DefaultItemAnimator());
    updatelist();
    re.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
        @Override public void onItemClick(View view, int position) {
            //startActivity(new Intent(getActivity(), delivery.class));
            //sub_category sub_category = new sub_category();
            FragmentManager fragMgr = getFragmentManager();
            FragmentTransaction ft = fragMgr.beginTransaction();
            ft.addToBackStack(null);
            ft.replace(R.id.view_pager, new sub_category(), TAG);
            ft.commit();
        }
    }));
    return view;
}

private void updatelist() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    categoryModelList = categoryParser.parseFeedCategory(response);
                    categoryAdapter categoryAdapter = new categoryAdapter(categoryModelList,getActivity().getApplicationContext());

                    re.setAdapter(categoryAdapter);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Toast.makeText(getActivity(),"اینترنت خود را چک کنید",Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    queue.add(stringRequest);
}}

当我点击recyclerview项目时,第一页会显示白色视图。

1 个答案:

答案 0 :(得分:0)

您可以在片段布局中添加frameLayout并替换

        FragmentManager fragMgr = getFragmentManager();
        FragmentTransaction ft = fragMgr.beginTransaction();
        ft.addToBackStack(null);
        ft.replace(R.id.view_pager, new sub_category(), TAG);
        ft.commit();

使用:

getChildFragmentManager().beginTransaction().add(*frameLayout ID* , new sub_category(), tag).commit();