标签不填充tablayout

时间:2015-07-21 12:07:34

标签: java android

标签不会像this

那样填充标签布局

如何在每tab == max width/2

时完成标签布​​局

主要活动java:

ViewPager mviewPager = (ViewPager)findViewById(R.id.pager);
    mviewPager.setAdapter(new viewpager(getSupportFragmentManager(),MainActivity.this));

    tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(mviewPager);

主要活动xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/Colorprimary"
    android:elevation="4dp"
    android:id="@+id/my_tool_bar"
   />

<android.support.design.widget.TabLayout
    android:id="@+id/sliding_tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="scrollable"
    />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/pager"
    android:layout_weight="1"
    />

片段寻呼机apdater java:

    package com.example.smite.floater;


import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Switch;

public class viewpager extends FragmentPagerAdapter {

    final int fragments_counter=2;
    private String titles[] = new String[]{"main","creator"};
    private Context context;

    public viewpager(FragmentManager fm , Context context){
        super(fm);
        this.context = context;
    }

    @Override
    public int getCount() {
        return fragments_counter;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){

            case 0:
                return new main();
            case 1:
                default:
                return new creator();
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return titles[position];
    }

}

我的应用主题为parent="Theme.AppCompat.Light.NoActionBar"

感谢帮助(:

1 个答案:

答案 0 :(得分:4)

如果你放行"app:tabMode="scrollable",那么tablayout宽度将不会填满整个屏幕。最好的解决方案就是这样。 把这一行放在XML

    app:tabMode="fixed"

在Java中,做

    if(tabLayout.getTabCount() > MAX_NUMBER) {
       tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

MAX_NUMBER是一些数字,具体取决于您的要求。我用过3,你可以使用3,4或任何适合你的要求。 这将确保如果只有几个标签,它们将占据整个宽度,如果没有,则可以滚动。