更改TabLayout中Tab的背景并不能在Scrollable tabMode中保持适当的空间使用第一个选项卡

时间:2018-01-12 07:30:02

标签: android android-tablayout

我尝试将背景图像设置为选定的标签,但是当使用可滚动的标签模式时,我遇到了标签将不需要的间距添加到第一个标签的问题。

不知道被困在哪里,请帮助我。

提前致谢。

DemoActivity.java

public class DemoActivity extends AppCompatActivity {
private CustomTabLayout mTabLayout;
private CustomViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);

    viewPager = findViewById(R.id.viewpager);
    mTabLayout = findViewById(R.id.tabs);

    final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
    if (viewPager != null)
        viewPager.setAdapter(pagerAdapter);
    //viewPager.setOffscreenPageLimit(2);
    if (mTabLayout != null) {
        mTabLayout.setupWithViewPager(viewPager);

        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null)
                tab.setCustomView(pagerAdapter.getTabView(i));
        }

        mTabLayout.getTabAt(0).getCustomView().setSelected(true);
    }
    pagerAdapter.SetOnSelectView(mTabLayout, 0);

    mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int c = tab.getPosition();
            pagerAdapter.SetOnSelectView(mTabLayout, c);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            int c = tab.getPosition();
            pagerAdapter.SetUnSelectView(mTabLayout, c);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.setPagingEnabled(false);
}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public final int PAGE_COUNT = 5;
    TextView title;
    private final String[] mTabsTitle = {"Events", "News", "Contacts", "History", "Settings"};

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View view = LayoutInflater.from(DemoActivity.this).inflate(R.layout.custom_tab_layout, null);
        title = (TextView) view.findViewById(R.id.title);
        title.setText(mTabsTitle[position]);
        return view;
    }

    public void SetOnSelectView(TabLayout tabLayout, int position) {
        TabLayout.Tab tab = tabLayout.getTabAt(position);
        View selected = tab.getCustomView();
        TextView iv_text = (TextView) selected.findViewById(R.id.title);
        iv_text.setTextColor(getApplicationContext().getResources().getColor(R.color.yellow));
    }

    public void SetUnSelectView(TabLayout tabLayout, int position) {
        TabLayout.Tab tab = tabLayout.getTabAt(position);
        View selected = tab.getCustomView();
        TextView iv_text = (TextView) selected.findViewById(R.id.title);
        iv_text.setTextColor(getApplicationContext().getResources().getColor(R.color.gray));
    }

    @Override
    public Fragment getItem(int pos) {

        switch (pos) {

            case 0:
                return NewTestFragment.newInstance("", "");


            case 1:
                return NewTestFragment.newInstance("", "");

            case 2:
                return NewTestFragment.newInstance("", "");

            case 3:
                return NewTestFragment.newInstance("", "");

            case 4:
                return NewTestFragment.newInstance("", "");
        }

        return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mTabsTitle[position];
    }
}

}

activity_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<info.androidhive.materialtabs.cards.CustomTabLayout
    android:id="@+id/tabs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    app:tabGravity="fill"
    app:tabIndicatorHeight="0dp"
    app:tabMode="scrollable" />

<info.androidhive.materialtabs.cards.CustomViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

style.xml

<style name="Base.Widget.Design.TabLayout" parent="android:Widget" 
 tools:ignore="PrivateResource">
    <item name="tabBackground">@drawable/tab_background</item>
    <item name="tabIndicatorColor">#ff00ff</item>
    <item name="tabIndicatorHeight">0dp</item>
</style>

tab_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_tab" android:state_selected="true" />
<item android:drawable="@drawable/tab_background_unselected" android:state_selected="false" android:state_focused="false" android:state_pressed="false" />
</selector>

tab_background_unselected.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
 <solid android:color="#333173" />
</shape>

ic_tab.png图标

ic_tab.png

CustomTabLayout代码

public class CustomTabLayout extends TabLayout {
private static final int HEIGHT_INDEX = 1;
private static final int WIDTH_INDEX = 0;
private static final int DIVIDER_FACTOR = 3;
private static final String SCROLLABLE_TAB_MIN_WIDTH = "mScrollableTabMinWidth";
private Typeface mTypeface;

private void init(){
    mTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Futura.ttf");
}

public CustomTabLayout(Context context) {
    super(context);
    init();
    initTabMinWidth();
}

public CustomTabLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
    initTabMinWidth();
}

public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
    initTabMinWidth();
}



private void initTabMinWidth() {

    int[] wh = getScreenSize(getContext());
    int tabMinWidth = wh[WIDTH_INDEX] / DIVIDER_FACTOR;

    Field field;
    try {
        field = TabLayout.class.getDeclaredField(SCROLLABLE_TAB_MIN_WIDTH);
        field.setAccessible(true);
        field.set(this, tabMinWidth);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

@Override
public void addTab(@NonNull Tab tab) {
    super.addTab(tab);

    ViewGroup mainView = (ViewGroup) getChildAt(0);
    ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
    View tabViewChild = tabView.getChildAt(1);
    ((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
}

@Override
public void setupWithViewPager(ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    if (mTypeface != null) {
        this.removeAllTabs();
        ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);

        PagerAdapter adapter = viewPager.getAdapter();

        for (int i = 0, count = adapter.getCount(); i < count; i++) {
            Tab tab = this.newTab();
            this.addTab(tab.setText(adapter.getPageTitle(i)));
            AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
            view.setTypeface(mTypeface, Typeface.NORMAL);
        }
    }
}

public static int[] getScreenSize(Context context) {
    int[] widthHeight = new int[2];
    widthHeight[WIDTH_INDEX] = 0;
    widthHeight[HEIGHT_INDEX] = 0;

    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();

    Point size = new Point();
    display.getSize(size);
    widthHeight[WIDTH_INDEX] = size.x;
    widthHeight[HEIGHT_INDEX] = size.y;

    if (!isScreenSizeRetrieved(widthHeight)) {
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        widthHeight[0] = metrics.widthPixels;
        widthHeight[1] = metrics.heightPixels;
    }

    // Last defense. Use deprecated API that was introduced in lower than API 13
    if (!isScreenSizeRetrieved(widthHeight)) {
        widthHeight[0] = display.getWidth(); // deprecated
        widthHeight[1] = display.getHeight(); // deprecated
    }

    return widthHeight;
}

private static boolean isScreenSizeRetrieved(int[] widthHeight) {
    return widthHeight[WIDTH_INDEX] != 0 && widthHeight[HEIGHT_INDEX] != 0;
}

}

0 个答案:

没有答案