Search code examples
androidandroid-tablayout

Can't arrange TabLayout icons to the left


In my project I have this code

tabLayout.getTabAt(0).setIcon(R.drawable.location);
tabLayout.getTabAt(1).setIcon(R.drawable.list);

that makes the icons appear on top of the text, and I need them to the left

I tried this:

ConstraintLayout cl = (ConstraintLayout) LayoutInflater.from(this).inflate(R.layout.tab, null);
TextView tab = cl.findViewById(R.id.textViewTab);
tab.setText("Ver mapa");
tab.setTextColor(getResources().getColor(R.color.tabActive));
tab.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.location, 0, 0, 0);
tabLayout.getTabAt(0).setCustomView(tab);

tab.setText("Ver lista");
tab.setTextColor(getResources().getColor(R.color.tabInactive));
tab.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.list, 0, 0, 0);
tabLayout.getTabAt(1).setCustomView(tab);

But I get this result

crappy tabs

Pretty, but not what I'm looking for


Solution

  • I forgot to initialize the second view:

    ConstraintLayout cl = (ConstraintLayout) LayoutInflater.from(this).inflate(R.layout.tab, null);
    TextView tab = cl.findViewById(R.id.textViewTab);
    tab.setText("Ver mapa");
    tab.setTextColor(getResources().getColor(R.color.tabActive));
    tab.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.location, 0, 0, 0);
    tabLayout.getTabAt(0).setCustomView(tab);
    
    tab = cl.findViewById(R.id.textViewTab); // This was missing     tab.setText("Ver lista");
    tab.setTextColor(getResources().getColor(R.color.tabInactive));
    tab.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.list, 0, 0, 0);
    tabLayout.getTabAt(1).setCustomView(tab);