TabLayout测量

时间:2016-10-18 14:16:39

标签: android android-layout android-viewpager

我正在使用TabLayout创建我的标签。问题是,当试图在代码中测量它时它给我0宽度。现在,我不确定我是做错了什么,或者系统究竟是什么意思为0宽。

我需要的是在膨胀后测量TabLayout宽度。我希望它只有在宽度大于屏幕宽度时才能滚动,如果它的宽度较小,我想让它居中。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.yrs.androidltx.features.adapterviews.viewpager.WithViewPagerActivity"
    >
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

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

    <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            >
    </android.support.v4.view.ViewPager>
</LinearLayout>

用这段代码核对后:

@Override
protected void onStart() {
   super.onStart();

   TabLayout.Tab tab1 = null;
   View customView = null;
   try {

       int width = tabLayout.getMeasuredWidth();
       Log.i(BuildConfig.DEV_TAG, "Tab Layout measured width: " + width);

       tab1 = tabLayout.getTabAt(1);
       customView = tab1.getCustomView();
       int tabWidth = customView.getWidth();
       Log.i(BuildConfig.DEV_TAG, "Tab 0 width: " + tabWidth);

       int tabMeasuredWidth = customView.getMeasuredWidth();
       Log.i(BuildConfig.DEV_TAG, "Tab 0 measured width: " + tabMeasuredWidth);

   } catch (NullPointerException ex) {
       Log.e(BuildConfig.DEV_TAG, "Exception: NullPointer on TabLayout");

   } catch (Exception ex) {
       Log.e(BuildConfig.DEV_TAG, "Exception: Debug it!");

   } finally {
       Log.i(BuildConfig.DEV_TAG, "Report Tab: " + tab1);
       Log.i(BuildConfig.DEV_TAG, "Report Tab (custom view): " + customView);
   }
}

我得到零和空指针。

1 个答案:

答案 0 :(得分:1)

在充气和测量后测量视图。请使用ViewTreeObserver

tabLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            tabLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        } else {
                            tabLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                        //measure your views
                    }
                });
            }