android – 我需要为使用viewpager和tablayout创建的标签分配一个唯一的标签ID吗?

前端之家收集整理的这篇文章主要介绍了android – 我需要为使用viewpager和tablayout创建的标签分配一个唯一的标签ID吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用viewpager和Tablayout创建了一个基于Tab的应用程序.当我单击一个按钮时,会创建带有子片段的新选项卡.

我需要的是为我的标签指定不同的标签ID,每个标签都应该不同.我试过我采取标签的位置但不幸的是,它不起作用.当我尝试使用下面的代码来烘烤位置时,它最初只在创建第一个选项卡时起作用,而对于创建的其他选项卡不起作用.我不知道为什么会这样.另外,如果我删除标签,则位置不正确.

所以我需要一个替代解决方案来为每个创建的新标签分配一个TAB ID(数字或名称),以便在创建每个标签时,我需要向具有该标识的服务器调用请求,并根据标签ID填充数据

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());
            }
        });

我的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(),"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,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child,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?tabid="{TAB ID HERE},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);
        }
    }
}

父母碎片:

public class FragmentParent extends Fragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private ImageView add;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,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));
        }
    }
}

请帮助我解决这个问题

解决方法

以下是我对该问题的解决方案:

首先,在名为ids.xml的res / values下创建一个id文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="tab_id_one" type="id"/>
    <item name="tab_id_two" type="id"/>
</resources>

然后,在创建选项卡的代码中,执行以下操作:

for (int i = 0; i< tabLayout.getTabCount(); i++) {
        TabLayout.Tab mTab = tabLayout.getTabAt(i);
        if (mTab != null) {
            switch (i){
                case 0:
                    View tabViewOne = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
                    tabViewOne.setId(R.id.tab_id_one);
                    //ect..
                    break;
                case 1:
                    View tabViewTwo = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
                    tabViewTwo.setId(R.id.tab_id_two);
                    //ect..
                    break;
                case 2:
                    //etc..
            }
        }
    }

注意:视图tabViewOne和tabViewTwo可以成为全局变量,它可以在类/活动/片段中的任何位置访问它们的ID.

猜你在找的Android相关文章