在Tablayout中使滚动或固定模式获得动态的Tabs数量 [英] make Scrollable or fixed mode in Tablayout for dynamic number of Tabs
问题描述
我希望tabMode 可与tabFrolled一起使用标签(具有单行标题). 在我的应用中,Tab的数量及其标题是动态的.我该怎么处理 当我设置给定的属性.标签标题以两行显示.当标签数量更大时.
I want tabMode scrollable with tabFilled with tabs(having single line title). As number of Tab and their title is dynamic in my app. How could I handle them when I set given property. Title of tabs come's in two lines.when number of tab is greater.
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
,并且当标签数量较少且tabMode设置为可滚动时.然后显示如下所示的多余空间.
and when number of tabs are less and tabMode is set to scrollable. then extra space shown like below.
我怎样才能使Tablayout可以在所有电话中以一行文字显示. 只需删除第二个屏幕的空格,并为第一张图像制作一行.
how could I make a Tablayout to work in all phones and with one line text . Simply remove spaces for second screen and make single line for 1st Image.
我知道我必须change it's tabMode and tabGravity for these two cases
,但是我怎么知道何时更改它的tabMode和tabGravity.可能的情况是,我只有三个选项卡,但是它们的标题很长,并且它们占据了整个空间.有时我们有5个标签的小标题.它们很适合放在屏幕上.
I know I have to change it's tabMode and tabGravity for these two cases
but How could I know when to change it's tabMode and tabGravity. It may be a case that I have only three tab's but their title are long and they are filling entire space. and some time we have 5 tabs with little title . They easily fit's in screen.
推荐答案
我想出了一个新的更好的解决方案.
I come up with a new and better solution..
List<String> titleTabs = getTitleOfTab();
for (String module : titleTabs) {
mTabLayout.addTab(mTabLayout.newTab().setText(module));
}
mTabLayout.post(new Runnable()
{
@Override
public void run()
{
// don't forget to add Tab first before measuring..
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int widthS = displayMetrics.widthPixels;
mTabLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int widthT = mTabLayout.getMeasuredWidth();
if (widthS > widthT) {
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
mTabLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
});
其中xml中的布局必须具有 tabGravity Fill 和 tabMode变为可滚动
where tablayout in xml must have tabGravity Fill and tabMode to Scrollable
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minHeight="?attr/actionBarSize"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"/>
这篇关于在Tablayout中使滚动或固定模式获得动态的Tabs数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!