android – 自定义视图可以用作TabItem吗?
作者:互联网
android中的TabLayout类为您提供了一个TabItem,可以让您指定文本和图标.
是否可以将自定义视图用作TabItem?
我的标签看起来像这样
正如你可以看到的除了图标和文字标签之外,我还有一个通知符号(黄色圆圈内的数字).我该如何制作这样的标签?
解决方法:
在某些情况下,我们可能希望为每个选项卡应用自定义XML布局,而不是默认选项卡视图.要实现此目的,请在将滑动选项卡附加到寻呼机后迭代所有TabLayout.Tabs:
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类:
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;
}
}
有了这个,您可以为适配器中的每个页面设置任何自定义选项卡内容.
标签:android-tablayout,android,android-layout 来源: https://codeday.me/bug/20190928/1827829.html