如何在标签主机中添加图标而不是文本

时间:2016-06-28 13:05:23

标签: java android

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.TableLayout;
import android.widget.TabHost;

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewpagerAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar=(Toolbar)findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        tabLayout=(TabLayout)findViewById(R.id.tabLayout);
        viewPager=(ViewPager)findViewById(R.id.viewpager);
        viewpagerAdapter=new ViewPagerAdapter(getSupportFragmentManager());
        viewpagerAdapter.addFragments(new HomeFragment(),"Home");
        viewpagerAdapter.addFragments(new TopFreeFragment(),"TopFree");
        viewpagerAdapter.addFragments(new TopPaidFragment(),"TopPaid");
        viewPager.setAdapter(viewpagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        Home.setIndicator("",getResources().getDrawable(R.drawable.iconimage1_design));
        TopFree.setIndicator("",getResources().getDrawable(R.drawable.iconimage2_design));
        TopPaid.setIndicator("",getResources().getDrawable(R.drawable.iconimage3_design));
    }
}

在最后3个声明中,Home,TopFree,TopPaid,红色标记,我应该提供哪些文本而不是这三个名称。 任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:0)

您应该获得Tab个对象并致电setIcon

tabLayout.getTabAt(0).setIcon(R.drawable.iconimage1_design);
tabLayout.getTabAt(1).setIcon(R.drawable.iconimage2_design);
tabLayout.getTabAt(2).setIcon(R.drawable.iconimage3_design);

答案 1 :(得分:0)

如果要将文本指示符替换为自定义指示符,则可以使用此选项:

int numTabs = 3;
int resIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3};

for (int i = 0; i < numTabs; i++) {
    RelativeLayout tab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.your_custom_sliding_tab_indicator_layout, null);
    ((ImageView) tab.findViewById(R.id.tab_icon)).setImageResource(resIds[i]);
    //...
    //set other values (text, image source etc.)
    tabLayout.getTabAt(i).setCustomView(tab);
}

或者如果您只需使用图标,则使用@ Juan的代码或修改后的版本:

int numTabs = 3;
int resIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3};

for (int i = 0; i < numTabs; i++) {
    tabLayout.getTabAt(i).setIcon(resIds[i]);
}