2016-12-12 62 views
0

我创建了一个带有5个选项卡的TabLayout。我想创建一个像旧Instagram一样的菜单。所以对于第三个标签,我需要自定义视图,所以我会有不同的背景颜色。 我所做的到现在为止是这样的:Android自定义选项卡没有得到正确的尺寸

View view1 = getLayoutInflater().inflate(R.layout.custom_tab, null); 
    view1.findViewById(R.id.icon).setBackgroundResource(R.drawable.profile_btn); 


    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.home_btn)); 
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.tools_btn)); 
    tabLayout.addTab(tabLayout.newTab().setCustomView(view1)); 
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.countdown_btn)); 
    tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.user_btn)); 

但是我没有预期的结果。这就是我的意思: 正如你所看到的,我想要的背景颜色并不能填充特定选项卡的所有宽度。 TabLayout Custom Tab

Custom_tab.xml文件使用RelativeLayout的,在这里我设置背景色,这在它具有:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/icon" 
    android:adjustViewBounds="true" 
    android:scaleType="centerCrop" 
    android:layout_centerInParent="true"/> 

回答

0

如果您使用的是默认tablayout.setIcon()方法,那么你应该使用为所有选项卡。

tabLayout.addTab(tabLayout.newTab().setCustomView(view1)); 
tabLayout.addTab(tabLayout.newTab().setCustomView(view2)); 
tabLayout.addTab(tabLayout.newTab().setCustomView(view3)); 
tabLayout.addTab(tabLayout.newTab().setCustomView(view4)); 
tabLayout.addTab(tabLayout.newTab(.setCustomView(view5)); 

然后,您将获得所有选项卡的正确尺寸。

+0

我的朋友,我只是做了这个,但我没有得到预期的结果:/ –