Android Tab Layout带有圆角的选项卡

24

这种类型的问题以前已经被问过,但是没有得到任何正确、有效的解决方案,所以我再次发布这个问题。很抱歉再次提问并浪费了您的时间。 请给出一些有效的解决方案。或者让我知道如果我做错了什么。 提前谢谢。

期望的标签:选择选项卡时应该显示如下

但实际上却是如下:

当前标签 当前标签

在页面加载时,选项卡会像“期望的标签”图像一样出现,但在选择后会变成“当前标签”图像。 MainXML 代码:

 <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                style="@style/MyCustomTabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/background_img_jpeg"
                android:minHeight="10dp"
                android:padding="10dp"
                app:tabGravity="fill"
                app:tabIndicatorColor="@color/TRANSPARENT"
                app:tabMode="fixed"
                app:tabTextColor="@color/blue" />

@style/MyCustomTabLayout

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabBackground">@drawable/tab_bg</item>
    </style>

@drawable/tab_bg

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:drawable="@drawable/tab_bgselected" />
    <item android:drawable="@drawable/tab_bgnotselected" />
    </selector>

@drawable/tab_bgselected

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:bottom="0dp"  android:top="0dp"
          android:left="0dp" android:right="0dp" >
        <shape android:shape="rectangle">
            <solid android:color="@color/blue" />
            <corners
                android:topLeftRadius="10dp"
                android:bottomLeftRadius="10dp">
            </corners>
        </shape>
    </item>
</layer-list>

就像这样 @drawable/tab_bgnotselected

在代码后面,我已经写了:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                try {
                    mViewPager.setCurrentItem(tab.getPosition());
                    TabPosition = tab.getPosition();
                    TabCount = tabLayout.getTabCount();

                    try {
                        if (TabPosition == 0) {
                            GradientDrawable drawable = (GradientDrawable) getResources().getDrawable(R.drawable.policy_tab_blue);
                            drawable.setCornerRadii(new float[]{10,10,0,0,0,0,10,10}); // this will create the corner radious to left side

                        } else {
                            GradientDrawable drawable = (GradientDrawable) getResources().getDrawable(R.drawable.policy_tab_white);
                            drawable.setCornerRadii(new float[]{0,0,10,10,10,10,0,0}); // this will create the corner radious to right side

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.i("TabPosition:--->", TabPosition + "");
                    Log.i("TabCount:--->", TabCount + "");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                try {

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
8个回答

31
你可以使用具有适当cardCornerRadiusMaterialCardView作为TabLayout的父布局,以实现这种单侧圆角背景。然后,您可以使用tabIndicatorColor来着色选定的选项卡布局。希望这能帮到您。谢谢。

代码片段

<com.google.android.material.card.MaterialCardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    app:strokeWidth="2dp"
    app:strokeColor="?attr/colorAccent"
    app:cardCornerRadius="20dp">
    <com.google.android.material.tabs.TabLayout
        app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
        android:id="@+id/tab_layout"
        app:tabIndicatorGravity="stretch"
        app:tabMaxWidth="0dp"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabIndicatorColor="?attr/colorAccent"
        app:tabSelectedTextColor="@android:color/white"
        app:tabTextColor="?attr/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="35dp"/>
</com.google.android.material.card.MaterialCardView>

输出在此输入图片描述


9

如果有人想要实现如下所示的选项卡布局(如下图所示),请参考以下内容:

first tab selected

saved tab selected

在 Xml 中使用 TabLayout 元素

<com.google.android.material.tabs.TabLayout
        android:id="@+id/images_videos_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_20sdp"
        android:layout_marginStart="@dimen/_10sdp"
        android:layout_marginEnd="@dimen/_10sdp"
        android:layout_marginTop="@dimen/_10sdp"
        android:background="@drawable/tabview_bg"
        app:tabGravity="fill"
        app:tabIndicatorColor="@android:color/transparent"
        app:tabMode="fixed"
        app:tabIndicatorHeight="0dp"
        app:tabRippleColor="@null"
        app:tabSelectedTextColor="@android:color/white"
         />

在你的活动/片段中

为了简洁起见,仅添加自定义代码

val tabCount: Int = images_videos_tab_layout.tabCount

    for (i in 0 until tabCount) {
        val tabView: View = (images_videos_tab_layout.getChildAt(0) as ViewGroup).getChildAt(i)
        tabView.requestLayout()
        ViewCompat.setBackground(tabView,setImageButtonStateNew(requireContext()));
        ViewCompat.setPaddingRelative(tabView, tabView.paddingStart, tabView.paddingTop, tabView.paddingEnd, tabView.paddingBottom);
    }

fun setImageButtonStateNew(mContext: Context): StateListDrawable {
    val states = StateListDrawable()
    states.addState(intArrayOf(android.R.attr.state_selected), ContextCompat.getDrawable(mContext, R.drawable.tab_bg_normal_blue))
    states.addState(intArrayOf(-android.R.attr.state_selected), ContextCompat.getDrawable(mContext, R.drawable.tab_bg_normal))

    return states
}

在Drawable中:
1. tab_bg_normal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent" />
</shape>

2.tab_bg_normal_blue

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/baseThemeColor" />
<corners android:radius="25dp" />
</shape>

3.tabview_bg

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp"/>
<stroke android:color="@color/baseThemeColor" android:width="1dp"/>
<solid android:color="#00000000"/>
</shape>

9

以下代码的结果:

enter image description here

使用4个形状(无需选择器),例如:

  1. tab_left_select.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item >
            <shape android:shape="rectangle">
                <solid android:color="@color/blue" />
                <corners
                    android:topLeftRadius="8dp"
                    android:bottomLeftRadius="8dp">
                </corners>
            </shape>
        </item>
    </layer-list>
    
  2. tab_left_unselect.xml

    • Same as above just change the color.
  3. tab_right_select.xml

    • Same as above just change the radius direction to right.
  4. tab_right_unselect.xml

    • Same as above just change the color and radius direction to right.
在您的布局中:
<android.support.design.widget.TabLayout
        android:layout_margin="@dimen/activity_vertical_margin"
        android:id="@+id/tabs"
        app:tabTextColor="@color/white"
        app:tabSelectedTextColor="@color/white"
        app:tabIndicatorColor="#00000000"
        android:layout_width="match_parent"
        android:layout_height="40dp" />

在你的Activity/Fragment中:
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
        setTabBG(R.drawable.tab_left_select,R.drawable.tab_right_unselect);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tabLayout.getSelectedTabPosition()==0) {
                    setTabBG(R.drawable.tab_left_select,R.drawable.tab_right_unselect);
                }
                else {
                    setTabBG(R.drawable.tab_left_unselect,R.drawable.tab_right_select);
                }
            }
            ....
        });

private void setTabBG(int tab1, int tab2){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
            ViewGroup tabStrip = (ViewGroup) tabLayout.getChildAt(0);
            View tabView1 = tabStrip.getChildAt(0);
            View tabView2 = tabStrip.getChildAt(1);
            if (tabView1 != null) {
                int paddingStart = tabView1.getPaddingStart();
                int paddingTop = tabView1.getPaddingTop();
                int paddingEnd = tabView1.getPaddingEnd();
                int paddingBottom = tabView1.getPaddingBottom();
                ViewCompat.setBackground(tabView1, AppCompatResources.getDrawable(tabView1.getContext(), tab1));
                ViewCompat.setPaddingRelative(tabView1, paddingStart, paddingTop, paddingEnd, paddingBottom);
            }

            if (tabView2 != null) {
                int paddingStart = tabView2.getPaddingStart();
                int paddingTop = tabView2.getPaddingTop();
                int paddingEnd = tabView2.getPaddingEnd();
                int paddingBottom = tabView2.getPaddingBottom();
                ViewCompat.setBackground(tabView2, AppCompatResources.getDrawable(tabView2.getContext(), tab2));
                ViewCompat.setPaddingRelative(tabView2, paddingStart, paddingTop, paddingEnd, paddingBottom);
            }
        }
    }

2
我认为你应该使用4个形状: 1)未选中的左侧按钮 2)选中的左侧按钮 3)未选中的右侧按钮 4)选中的右侧按钮。
然后编写选择器以用于按钮背景,例如左侧按钮(右侧按钮类似)的示例:
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_selected="true">
<shape android:shape="rectangle">
  <corners
    android:topRightRadius="10dp"
    android:bottomLeftRadius="10dp"/>
  <gradient
    android:startColor="#000"
    android:endColor="#000"
    android:gradientRadius="400"
    android:angle="-270"/>
</shape>
</item>

<item>
    <shape android:shape="rectangle">
      <gradient
        android:angle="90"
        android:startColor="#880f0f10"
        android:centerColor="#8858585a"
        android:endColor="#88a9a9a9"/>
   <corners
      android:topRightRadius="10dp"
      android:bottomLeftRadius="10dp"/>
</shape>
</item>

更多详细信息请访问此处。如何在Android中为选项卡设置圆角


在选择第二个选项卡之后,它会出现如我的问题中提到的“来临选项卡”。 - ShutterSoul

1

这里有一个之前在StackOverflow上的答案,适用于创意开发者,但我不记得它在哪里了。可以通过将卡片视图作为TabLayout的父视图来轻松实现。

enter image description here

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include2"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabIndicatorHeight="0dp"
        app:tabSelectedTextColor="@color/white"
        app:tabTextAppearance="@style/AppTheme.CustomTabText"
        app:tabTextColor="@color/green">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Today’s menu" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Full Menu" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Reviews" />

    </com.google.android.material.tabs.TabLayout>

</androidx.cardview.widget.CardView>

0
我想分享我的答案:(在我的情况下,我只是在tabLayout上方添加了Cardview并设置了圆角半径)。
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/rlEmpty">

    <androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cvTab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="20dp"
        card_view:cardElevation="0dp">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/result_tabs_home"
            style="@style/customTabLayout2"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:background="@color/tab_color"
            android:elevation="0dp"
            app:tabIndicatorColor="@color/tab_indicator"
            app:tabMode="scrollable"
            app:tabTextAppearance="@style/customTabLayout" />
    </androidx.cardview.widget.CardView>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpagerhome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/cvTab" />
</RelativeLayout>

0

使用 Material-Design,我们可以通过使用 MaterialButtonToggleGroup 并为选项卡添加 MaterialButtons 来轻松实现。

<com.google.android.material.button.MaterialButtonToggleGroup
            android:id="@+id/buttonGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            app:checkedButton="@+id/nearest">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/nearest"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Nearest" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/alphabetical"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Alphabetical"/>

        </com.google.android.material.button.MaterialButtonToggleGroup>

请参考此链接以获取更多信息 - https://material.io/develop/android/components/material-button-toggle-group/


0

我认为你应该在所有角落使用 <div>

 <?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
         android:startColor="#SomeGradientBeginColor"
         android:endColor="#SomeGradientEndColor" 
         android:angle="270"/> 

    <corners 
         android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/> 
</shape> 

检查如何在按钮或布局中使用此功能

http://www.techamongus.com/2017/02/android-layouts-with-round-corners.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接