我使用SlidingTabLayout.java和SlidingTabStrip.java文件以及工具栏来创建可滑动的选项卡。
我现在跟随了几个不同的教程,并遇到了同样的问题,我的标签是如何显示的。我将setdistributeeven设置为true,并将代码更改为4个字符串而不是3个。现在,我的选项卡中的文本正在压缩,而不是将宽度设置为最大的字符串值,并允许在纵向模式下滑动时溢出。在景观中,这个问题不存在。https://i.stack.imgur.com/ILBaP.png vs https://i.stack.imgur.com/CXMuK.png
如果我删除一个字符串,问题就解决了,如果我添加另一个字符串,允许溢出,但它不再均匀地设置宽度,但它在横向上又工作得很好。
我的理论是,我的四个标签的计算宽度,给定的文本长度,是达到一些奇怪的"甜蜜"点的屏幕尺寸。它太大了,无法在一个屏幕上容纳自己,但也不足以引发溢出。
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_square);
Toolbar appToolbar = (Toolbar) findViewById(R.id.square_toolbar); //creates instance of app_toolbar to serve as actionbar
//setting toolbar to actionbar
setSupportActionBar(appToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false); //do not have app_toolbar Title
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager(), TheSquare.this));
//Give slidingTabLayout ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
//Center the tabs in the layout
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer(){
@Override
public int getIndicatorColor(int position){
return getResources().getColor(R.color.green);
}
});
slidingTabLayout.setViewPager(viewPager);
}
TabFragmentPagerAdapter.java
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
private String tabTitles[] = new String[] { "Featured", "News", "Sports", "Life"};
private Context context;
public TabFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<include
android:id="@+id/square_toolbar"
layout="@layout/app_toolbar"/>
<com.squareoffs.squareoffs.SlidingTabs.SlidingTabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="@android:color/white"/>
我有点没有测试的想法,谢谢你的帮助。
无法解决"为什么"的问题,除了我上面的理论,但我在每个字符串("News"到"News")中添加了空格,所以它们的长度相等,至少在这个特殊情况下,它解决了问题。这不是一个理想的解决方案,因为如果我想让文本占用相同的空间,我必须减少填充以确保所有内容在选项卡中看起来相似,但它至少显示正确。