我正在使用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);
}
}我得到了零和零指针。
发布于 2016-10-18 14:20:17
测量视图后,它们被充气和测量。为此,请使用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
}
});
}https://stackoverflow.com/questions/40110681
复制相似问题