创建或删除选项卡时,将重新启动所有视图

时间:2018-02-23 11:15:04

标签: android

我正在创建一个实现多个标签的应用程序,例如chrome tabs.A选项卡将保存子片段,在添加新标签时,将为新标签重新创建子片段。我面临的问题是,在我的子片段中,我有动态网格视图和列表视图。当我创建列表或网格然后新选项卡创建了列表并且网格被删除。删除标签时也会发生相同的情况。

如果已经有2个标签并且我添加了一个列表,我可以切换标签而不删除列表或网格。 我登录onActivityCreated和onStart进行测试,当我创建第二个选项卡onstart时调用2次,当我添加第3个选项卡时,它调用了3次并且喜欢!

如果我添加新标签页或删除其他标签,我需要在其他标签页中保留视图。

为什么会发生这种情况:

我的ViewPageradapter是:

    public class ViewPagerAdapter extends FragmentStatePagerAdapter {
        private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
        private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
        Context context;
        ViewPager viewPager;
        TabLayout tabLayout;
        int selectedTabPosition;
        private boolean doNotifyDataSetChangedOnce = false;
        public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
                                TabLayout tabLayout) {
            super(manager);
            this.context = context;
            this.viewPager = viewPager;
            this.tabLayout = tabLayout;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            if (doNotifyDataSetChangedOnce) {
                doNotifyDataSetChangedOnce = false;
                notifyDataSetChanged();
            }
            return mFragmentList.size();
        }

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

        public void removeFrag(int position) {
            removeTab(position);
            Fragment fragment = mFragmentList.get(position);
            mFragmentList.remove(fragment);
            mFragmentTitleList.remove(position);
            //destroyFragmentView(viewPager, position, fragment);
            notifyDataSetChanged();
            if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
            //viewPager.setCurrentItem(getCount() - 1);
            setupTabLayout();
        }

        public View getTabView(final int position) {
            View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
            TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
            ImageView tabItemAvatar =
                (ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
            ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
            if(getCount() == 1){
                remove.setVisibility(View.INVISIBLE);
            }
            else{
                remove.setVisibility(View.VISIBLE);
            }
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        Log.d("Remove", "Remove");
                        if(getCount() != 1){
                            removeFrag(position);
                        }
                        else{
                           // Toast.makeText("Atleast One Tab is requied")
                        }

                }
            });
            tabItemName.setText(mFragmentTitleList.get(position));
            tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
            tabItemAvatar.setImageResource(R.drawable.boy);
            return view;
        }
        public void setupTabLayout() {
            selectedTabPosition = viewPager.getCurrentItem();
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
                tabLayout.getTabAt(i).setCustomView(getTabView(i));
            }
        }

        public void removeTab(int position) {
            if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
                tabLayout.removeTabAt(position);

            }

        }


        @Override
        public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    } 


Parent Fragment:
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
        adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {
        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getCount() > 4){
                    Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
                }
                else {
                    Bundle bundle = new Bundle();
                    bundle.putString("data", "POS"+adapter.getCount());
                    FragmentChild fragmentChild = new FragmentChild();
                    fragmentChild.setArguments(bundle);
                    adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
                    adapter.notifyDataSetChanged();
                    if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

                    viewPager.setCurrentItem(adapter.getCount() - 1);
                    setupTabLayout();
                }
            }
        });
    }

    public void addPage(String pagename) {
        Bundle bundle = new Bundle();
        bundle.putString("data", pagename);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }

我的名单存在的儿童片段:

public class FragmentChild extends Fragment {
    String childname;
    TextView textViewChildName;
    EditText editText;
    private GridView mGridView;
    private ListItem mListItem;
    private ListView mListview;
    private ProgressBar mProgressBar;
    private ProductViewAdapter mGridAdapter;
    private ListViewAdapter mListAdapter = null;
    private ArrayList<GridItem> mGridData;
    private ArrayList<ListItem> mListData = null;
    ListView listView;
    CheckInterNetConnection check ;
    Boolean isInternetPresent = false;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        Bundle bundle = getArguments();
        childname = bundle.getString("data");
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        //textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
        //textViewChildName.setText(childname);
        //editText = (EditText) view.findViewById(R.id.editText);
        //editText.setText("");
    }

    private void setEvents() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("onActivityCreated","onActivityCreated");
        mGridView = (GridView) getView().findViewById(R.id.gridView);
        mGridData = new ArrayList<>();
        mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
        mGridView.setAdapter(mGridAdapter);

        mListview = (ListView) getView().findViewById(R.id.list);
        mListData = new ArrayList<>();
        mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
        mListview.setAdapter(mListAdapter);

    }
    @Override
    public void onStart() {
        super.onStart();
        Log.e("onSTart","onSTart");
        check = new CheckInterNetConnection(getActivity());
        isInternetPresent = check.isConnectingToInternet();
        if (isInternetPresent) {
            //fetchProducts();
        }
    }
    public void fetchProducts(){
        Log.e("URL","http://13.126.17.194/products.php");
        RestClientHelper.getInstance().get("http://13.126.17.194/products.php", new RestClientHelper.RestClientListener() {
            @Override
            public void onSuccess(String response) {
                parseResult(response);
                mListData.clear();
                mListAdapter.setGridData(mListData);
                mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                        try {
                            ListItem items;
                            GridItem item = (GridItem) parent.getItemAtPosition(position);
                            items = new ListItem();
                            items.setName(item.getTitle());
                            items.setType(item.getDescription());
                            mListData.add(items);
                        }
                        catch(Exception e){

                        }
                        finally {
                            mListAdapter.setGridData(mListData);
                        }
                    }
                });
            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("products");
            GridItem item;
            if(posts.length() <= 0){
                RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
                ly.setVisibility(View.VISIBLE);
            }
            else {
               // RelativeLayout ly = (RelativeLayout)  getView().findViewById(R.id.noOps);
                //ly.setVisibility(View.INVISIBLE);
                for (int i = 0; i < posts.length(); i++) {
                    JSONObject post = posts.optJSONObject(i);
                    String id = post.optString("id");
                    String title = post.optString("name");
                    String description = post.optString("description");
                    String image = post.optString("image");
                    String qty = post.optString("qty");
                    String quantityin = post.optString("quantityin");
                    String price = post.optString("price");

                    item = new GridItem();
                    item.setId(id);
                    item.setTitle(title);
                    item.setDescription(description);
                    item.setImage(image);
                    item.setQuantity(qty);
                    item.setQuantityIn(quantityin);
                    item.setUnitprice(price);
                    mGridData.add(item);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finally {
            mGridAdapter.setGridData(mGridData);
        }
    }
}

PARENT FRAGMENT:

public class FragmentParent extends Fragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private ImageView add;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
        adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {
        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getCount() > 4){
                    Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
                }
                else {
                    Bundle bundle = new Bundle();
                    bundle.putString("data", "POS"+adapter.getCount());
                    FragmentChild fragmentChild = new FragmentChild();
                    fragmentChild.setArguments(bundle);
                    adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
                    adapter.notifyDataSetChanged();
                    if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

                    viewPager.setCurrentItem(adapter.getCount() - 1);
                    setupTabLayout();
                }
            }
        });
    }

    public void addPage(String pagename) {
        Bundle bundle = new Bundle();
        bundle.putString("data", pagename);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        //setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }
}

更新

我能够多次解决gridview更新,但是如果我添加或删除标签,视图仍会重新初始化。请帮忙

0 个答案:

没有答案