Я использую 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);
}
}
Я получаю нули и пустые указатели.
Я также пробовал использовать метод .post() и, похоже, работает. ViewTreeObserver для меня новичок. Я буду исследовать его дальше и протестировать ваш код. – shadox