I need to assign a unique tab id to my tabs created using viewpager and tablayout?
Asked Answered
E

3

10

I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.

What I need is to assign different tab id to my tabs and each should be different. I tried i take the position of tabs but unfortunately, it doesn't work. when i tried to toast the position using below code it works only initially when the first tab is created and doesn't work for other tabs created. I don't know why this happens. ALso if i delete the tabs the position is not getting correct.

So I need an alternative solution to assign a TAB id (number or name) to each new tabs created so that when each tab is created I need to call a request to server with that id and populate data based on the tab 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());
            }
        });

My ViewPageradapter is:

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

CHILD FRAGMENT :

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

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

PLEASE HELP ME TO SOLVE THIS

Electrobiology answered 23/2, 2018 at 14:41 Comment(0)
V
5

Here is my solution for the question:

First, create an id file under res/values named ids.xml:

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

Then, within the code where tabs are created, do the following:

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..
            }
        }
    }

Note: Views tabViewOne and tabViewTwo can be made global variables where it will give access to their ids anywhere within the class/activity/fragment.

Victualer answered 26/6, 2018 at 16:57 Comment(0)
I
1

In your viewPager Adapter extends FragmentPagerAdapter this and include these methods and it will give new ID to every Fragment and when you add manually data in array and call notifyDataSetChange(), also call this method notifyChangeInPosition(mItems.size() - 1);.

From this the added item get a new ID.

  private long baseId = 0;

    ViewPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return mItems.size();
    }
//this is called when notifyDataSetChanged() is called
    @Override
    public int getItemPosition(Object object) {
        // refresh all fragments when data set changed
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public long getItemId(int position) {
        // give an ID different from position when position has been changed
        return baseId + position;
    }

    /**
     * Notify that the position of a fragment has been changed.
     * Create a new ID for each position to force recreation of the fragment
     *
     * @param n number of items which have been changed
     */
    void notifyChangeInPosition(int n) {
        // shift the ID returned by getItemId outside the range of all previous fragments
        baseId += getCount() + n;
    }
Interpellant answered 2/7, 2018 at 10:48 Comment(0)
K
0

You can use the setTag() method of TabLayout.Tab to use any Object you want as an identifier. You could do this in your setupTabLayout() method, where you are setting your custom view for each Tab.

For example, to use a String:

tabLayout.getTabAt(i).setTag("tab_" + i);

You can then later check the tag of each tab in your parent fragment with tab.getTag();

Kishakishinev answered 25/6, 2018 at 23:48 Comment(1)
My intent is to set a unique view id for each tab because I would like to test my layout view after I click on a tab using Android Espresso. This thread is related to what I'm trying to achieve here: #51029455Victualer

© 2022 - 2024 — McMap. All rights reserved.