片段消失了

时间:2016-04-01 12:00:09

标签: java android android-layout android-fragments android-tablayout

我有一个片段alertsfragment.java,它有一个网格视图布局,当我打开它时,它正常工作,但是一旦我在其他选项卡之间滑动,它就会消失。 为了解释更多,我有一个活动标签布局,底部有一个标签,其第一个标签打开两个片段alertsfragment和friendsfragment, 我包括代码和屏幕截图以简化。

盯着mapfragment,其中包含两个片段alert frag和friends frag

mapfragment.java

public class MapFragment extends Fragment{
     TabLayout tabLayout;
     ViewPager viewPager;


    public MapFragment()
    {

        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View ROOTView =inflater.inflate(R.layout.mapfragment,container,false);
        viewPager = (ViewPager)ROOTView.findViewById(R.id.viewpager2);
        setupViewPager(viewPager);
        tabLayout = (TabLayout)ROOTView.findViewById(R.id.tabs);
        //viewPager.setOffscreenPageLimit(2);
        tabLayout.setupWithViewPager(viewPager);

         return ROOTView;
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
        adapter.addFragment(new FriendsFragment(), "FRIENDS");
        adapter.addFragment(new AlertsFragment(), "Alerts");
        setRetainInstance(true);
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter
    {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {

            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {

            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return mFragmentTitleList.get(position);
        }
    }



}

alertsfragment.java

public class AlertsFragment extends Fragment{
    GridView grid;
    final String[] name = {
            "Google",
            "Github",
            "Instagram",
            "Facebook",
    } ;
     final String[] status = {
            "Google",
            "Github",
            "Instagram",
            "Facebook",
    } ;
     final String[] place = {
            "Google",
            "Github",
            "Instagram",
            "Facebook",
    } ;
   final  int[] imageId = {
            R.drawable.logo,
            R.drawable.logo,
            R.drawable.logo,
            R.drawable.logo,
    };

    public AlertsFragment()
    {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View alertsfrag =inflater.inflate(R.layout.alertsfragments,container,false);
        grid=(GridView) alertsfrag.findViewById(R.id.grid);

        CustomGrid adapter = new CustomGrid(getActivity(), name,status,place,imageId);
        grid=(GridView)alertsfrag.findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(), "You Clicked at " +name[+ position], Toast.LENGTH_SHORT).show();

            }
        });

        return alertsfrag;
    }
}

其惯用手册

public class CustomGrid extends BaseAdapter{
    private Context mContext;
    private final String[] name;
    private final String[] status;
    private final String[] place;
    private final int[] Imageid;

    public CustomGrid(Context c,String[] name,String[] status,String[] place,int[] Imageid ) {
        mContext = c;
        this.Imageid = Imageid;
        this.name = name;
        this.status = status;
        this.place = place;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return name.length;
      //  return status.length;
      //  return place.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            TextView textView1 = (TextView) grid.findViewById(R.id.grid_text1);
            TextView textView2 = (TextView) grid.findViewById(R.id.grid_text2);
            ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
            textView.setText(name[position]);
            textView1.setText(status[position]);
            textView2.setText(place[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

它的XML alertsfrag.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"
    tools:context=".AlertsFragment" >

    <GridView
        android:layout_marginTop="60dp"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/grid"
        />

</LinearLayout>

mainTabLayout

TabLayout.java

public class Bottom_Tabs_Activity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_friends,
            R.drawable.ic_map,
            R.drawable.ic_status,
            R.drawable.ic_chat,
            R.drawable.ic_profile
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabs);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null)
            setupViewPager(viewPager);
        else {
            Log.e("test", "i am null");
        }
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        setupTabIcons();
    }
        private void setupTabIcons() {
            tabLayout.getTabAt(0).setIcon(tabIcons[0]);
            tabLayout.getTabAt(1).setIcon(tabIcons[1]);
            tabLayout.getTabAt(2).setIcon(tabIcons[2]);
            tabLayout.getTabAt(3).setIcon(tabIcons[3]);
            tabLayout.getTabAt(4).setIcon(tabIcons[4]);
        }

    private void setupViewPager(ViewPager viewPager)
    {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new MapFragment(),"MAPS");
        adapter.addFrag(new PeopleFragment(),"PEOPLE");
        adapter.addFrag(new HomeFragment(),"HOME");
        adapter.addFrag(new ChatFragment(),"CHAT");
        adapter.addFrag(new ProfileFragment(),"PROFILE");

        viewPager.setAdapter(adapter);
    }
    class ViewPagerAdapter extends FragmentPagerAdapter
    {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        public ViewPagerAdapter(FragmentManager manager)
        {
            super(manager);
        }
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount() {
            return mFragmentList.size();
        }
        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        @Override
        public CharSequence getPageTitle(int position) {

            // return null to display only the icon
            return null;
        }
    }
}

TabLayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"

    android:layout_width="match_parent">

    <LinearLayout

        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:orientation="vertical"
        android:weightSum="1"

        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".9"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            app:tabMode="fixed"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".1"
            android:background="#000000"
            app:tabIndicatorColor="#ff1232"
            app:tabGravity="fill"
            />

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_gravity="bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            >
        </android.support.design.widget.AppBarLayout>



    </LinearLayout>

</LinearLayout>

截图

之前和之后 Before After

任何形式的帮助将不胜感激:)

2 个答案:

答案 0 :(得分:4)

需要使用getChildFragmentManager()而不是getFragmentManager()来放置和管理片段内的片段。

请参阅mapfragment.java,我使用了这个,问题解决了

答案 1 :(得分:0)

不要使用FragmentPagerAdapter。 你必须在ViewPagerAdapter Class上使用FragmentStatePagerAdapter。

 class ViewPagerAdapter extends FragmentStatePagerAdapter
    {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        public ViewPagerAdapter(FragmentManager manager)
        {
            super(manager);
        }
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount() {
            return mFragmentList.size();
        }
        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        @Override
        public CharSequence getPageTitle(int position) {

            // return null to display only the icon
            return null;
        }
    }