带有自定义视图选项卡的Android TabLayout - 图标点击不会切换选项卡
问题描述:
我有一个tabsLayout
三个选项卡,每个选项卡都包含一个自定义视图,其中包含一个ImageView
和一个TextView
。 当我想切换标签并点击其中一个标签时,如果我点击图标外部,它们会正确切换。但是,当我点击图标时,它们不会切换。 我该如何解决这个问题?带有自定义视图选项卡的Android TabLayout - 图标点击不会切换选项卡
我试着用可调焦=假,但它并没有为我工作。
我的自定义视图:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customButton"
android:layout_width="match_parent"
android:layout_height="80dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:alpha="0.5"
android:orientation="vertical">
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="0dp"
android:layout_weight="4"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:background="@android:color/transparent"
android:onClick="airspacesButtonOnClick"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:tint="@color/colorIcons"/>
<TextView
android:id="@+id/string"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAlignment="center"
android:textSize="12sp" />
</LinearLayout>
我TabLayout:
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="80dp"
app:tabIndicatorColor="@color/colorButton"
app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
最后我的Java代码:
int[] iconIds = {R.drawable.ic_profile, R.drawable.ic_plane, R.drawable.ic_document};
int[] labelIds = {R.string.menu, R.string.menu, R.string.menu};
View customView;
for (int i = 0; i < tabLayout.getTabCount(); i++) {
customView = getActivity().getLayoutInflater().inflate(R.layout.custom_icon, null);
customView.findViewById(R.id.icon).setBackgroundResource(iconIds[i]);
((TextView) customView.findViewById(R.id.string)).setText(labelIds[i]);
tabLayout.getTabAt(i).setCustomView(customView);
答
你尽量让你的ImageView无法点击设置clickable
为false但使用onClick
将覆盖它并且您的ImageView变成可点击的获得。这就是为什么点击ImageView被ImageView本身消耗而不传播给它的父级。因此,这条线在您的自定义标签布局的ImageView应删除:
android:onClick="airspacesButtonOnClick"
除了这条线,它为我工作与给定的代码和布局。
+0
就是这样,谢谢! :) – Simon
你能提供相关的代码吗? – Mehmed
@Mehmed我加了负责任的代码 – Simon