自定义视图可以用作 TabItem 吗? [英] Can a custom view be used as a TabItem?

查看:30
本文介绍了自定义视图可以用作 TabItem 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

android 中的 TabLayout 类为您提供了一个 TabItem,可以让您指定文本和图标.是否可以将自定义视图用作 TabItem?

The TabLayout class in android provides you with a TabItem that can let you specify a text and a icon. Is it possible to use a custom view as a TabItem?

我的标签看起来像这样

如您所见,除了图标和文本标签之外,我还有一个通知符号(黄色圆圈内的数字).我怎样才能制作这样的标签?

as you can see besides an icon and a text label, I also have a notification symbol (a number inside a yellow circle). how can I make tabs like this?

推荐答案

在某些情况下,我们可能希望为每个选项卡应用自定义 XML 布局而不是默认选项卡视图.为此,在将滑动选项卡附加到分页器后遍历所有 TabLayout.Tabs:

In certain cases, instead of the default tab view we may want to apply a custom XML layout for each tab. To achieve this, iterate over all the TabLayout.Tabs after attaching the sliding tabs to the pager:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SampleFragmentPagerAdapter pagerAdapter = 
            new SampleFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
        viewPager.setAdapter(pagerAdapter);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);

        // Iterate over all tabs and set the custom view
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }
    }

    //...
} 

接下来,我们将 getTabView(position) 方法添加到 SampleFragmentPagerAdapter 类中:

Next, we add the getTabView(position) method to the SampleFragmentPagerAdapter class:

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
   private String tabTitles[] = new String[] { "Tab1", "Tab2" };
   private int[] imageResId = { R.drawable.ic_one, R.drawable.ic_two };

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View v = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
        TextView tv = (TextView) v.findViewById(R.id.textView);
        tv.setText(tabTitles[position]);
        ImageView img = (ImageView) v.findViewById(R.id.imgView);
        img.setImageResource(imageResId[position]);
        return v;
    }

} 

通过它,您可以为适配器中的每个页面设置任何自定义选项卡内容.

With this you can setup any custom tab content for each page in the adapter.

来源

这篇关于自定义视图可以用作 TabItem 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆