一切正常,我从未遇到任何问题。 但不知何故,当我尝试接收不在第一个位置的Tab时,我现在得到一个空对象:
java.lang.NullPointerException:尝试调用虚方法' android.support.design.widget.TabLayout $ Tab android.support.design.widget.TabLayout $ Tab.setCustomView(android.view.View)& #39;在空对象引用上
在onCreateView中调用tabLayoutSetup。
private void tabLayoutSetup(){
// Get the ViewPager and set it's PagerAdapter so that it can display items
Bugger.t(context,"tablayout");
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
tabLayout.setupWithViewPager(viewPager);
createTabs();
}
//this method is creating all tabs for account's tablayout
private void createTabs(){
TabLayout.Tab ShareTab = tabLayout.getTabAt(0);
TabLayout.Tab MarkTab = tabLayout.getTabAt(1);
//***********************************************************************************************************
//inflating template for first tab, Activities.
View TabView = LayoutInflater.from(context).inflate(R.layout.account_tablayout_customtab, null); //template
TextView titel = (TextView) TabView.findViewById(R.id.tab_titel);
//populating first template for 'Activities'
titel.setText(getResources().getString(R.string.SharesTab));
titel.setTextColor(ContextCompat.getColor(context,R.color.tabLayout_active));
ShareTab.setCustomView(TabView);
//**********************************************************************************************************
//inflating template for second tab, Messages.
TabView = LayoutInflater.from(context).inflate(R.layout.account_tablayout_customtab, null); //template
titel = (TextView) TabView.findViewById(R.id.tab_titel);
//populating second template for 'Messages'
titel.setText(getResources().getString(R.string.MarkTab));
MarkTab.setCustomView(TabView);
这真的很奇怪,因为它之前运作顺利。在位置0(.getTabAt(0)
)接收选项卡根本不是问题。但是,我无法在第一个位置收到Tab。
XML:
<android.support.design.widget.TabLayout
android:id="@+id/account_tabLayout"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_marginTop="12dp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/account_bio">
</android.support.design.widget.TabLayout>
答案 0 :(得分:4)
您需要添加TabItems
。您可以在Layout XML中执行此操作。像这样:
<android.support.design.widget.TabLayout
android:id="@+id/account_tabLayout"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_marginTop="12dp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/account_bio">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_menu"
/>
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_favorites"
/>
</android.support.design.widget.TabLayout>
您应该能够为每个人TabItem
一个身份android:id="@+id/tabItemX1"
并直接访问它,而不是使用.getTabAt(0)