我正在将可滚动的TabLayout与ViewPager一起使用。
我想确保在任何给定时间每页显示7个选项卡。即使标签总数为10,我也希望每页有7个标签,然后滚动以显示其他3个标签。
我找不到控制显示的选项卡数量的属性。
答案 0 :(得分:0)
将此代码添加到您的MainActivity
ViewPager mpager;
TabPageAdapter adapter = new TabPageAdapter(getSupportFragmentManager(), list);
mtabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mpager.setOffscreenPageLimit(list.size());
mpager.setAdapter(adapter);
在您的xml标签布局文件中
app:tabMode="scrollable"
答案 1 :(得分:0)
在某些情况下,我们可能希望为每个选项卡应用自定义XML布局,而不是默认的选项卡视图。为此,请在将滑动式选项卡附加到分页器上之后遍历所有TabLayout.Tab:
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;
}
}
由此,您可以为适配器中的每个页面设置任何自定义选项卡内容。 您可以通过以下链接获取帮助: https://guides.codepath.com/android/google-play-style-tabs-using-tablayout
答案 2 :(得分:0)
最终对我有用的是计算每个单元格的所需大小,以获得每页所需的标签总数,然后在app:tabMaxWidth
内设置android.support.design.widget.TabLayout