2016-10-18 3 views
0

私はタブを作成するためにTabLayoutを使用しています。問題は、コードでそれを測定しようとすると、0の幅が与えられるということです。今、私が何か間違っているのか、正確には0幅でシステムが何を意味しているのか分かりません。TabLayout測定

私が必要とするのは、膨張後の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

膨らませて測定した後に測定を行います。それには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 
        } 
       }); 
      } 
+0

私も.post()メソッドで試してみましたが、動作しているようです。 ViewTreeObserverは私にとって初めてのものです。それをさらに調査し、コードをテストします。 – shadox