AppBarLayout中的Android TabLayout

In this tutorial, we’ll discuss and implement Android TabLayout in our android application. Also we’ll get into the details of Material Design.

在本教程中,我们将在我们的android应用程序中讨论和实现Android TabLayout。 另外,我们还将详细介绍Material Design。

Android TabLayout AppBarLayout (Android TabLayout AppBarLayout)

In the previous tutorials, we’ve been discussing the perks of using CoordinatorLayout as the root of our activity’s layout. All this while we haven’t gone into the details of an AppBarLayout and it’s usages. Let’s look into it now.

在先前的教程中,我们一直在讨论将CoordinatorLayout用作活动布局的基础的好处。 所有这些虽然我们还没有涉及AppBarLayout的细节及其用法。 让我们现在来看一下。

AppBarLayout (AppBarLayout)

AppBarLayout is a vertical LinearLayout that is generally the first child inside a CoordinatorLayout and acts as a wrapper for the ToolBar in most cases. Using the ToolBar as a direct child of CoordinatorLayout would work fine but it will not be able to coordinate with other child views present. Here’s where the importance of AppBarLayout arises. It allows it’s child views to achieve the desired scrolling behavior using the param app:layout_scrollFlags

AppBarLayout是垂直的LinearLayout,通常是CoordinatorLayout中的第一个子级,并且在大多数情况下充当ToolBar的包装。 将ToolBar用作CoordinatorLayout的直接子代可以正常工作,但无法与当前的其他子代视图进行协调。 这是AppBarLayout重要性的体现。 它允许其子视图使用参数app:layout_scrollFlags实现所需的滚动行为

A sample xml layout for the above description is given below:

下面给出了上述说明的示例XML布局:

<android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

The app:layout_scrollFlags attribute of the Toolbar indicates to the view how to respond. It has the following possible values.

工具栏的app:layout_scrollFlags属性向视图指示如何响应。 它具有以下可能的值。

  • scroll : This flag is generally set for all views that need to scroll off-screen. Views that don’t use this flag remain static allowing the other scrollable views to slide behind it

    scroll :通常为需要在屏幕外滚动的所有视图设置此标志。 不使用此标志的视图保持静态,从而允许其他可滚动视图在其后滑动
  • enterAlways : This flag ensures that any downward scroll will cause the view to become visible, enabling the quick return pattern

    enterAlways :此标志确保任何向下滚动都将导致视图变为可见,从而启用快速返回模式
  • enterAlwaysCollapsed : An additional flag for ‘enterAlways’ which modifies the returning view to only initially scroll back to it’s collapsed height.

    enterAlwaysCollapsed :'enterAlways'的附加标志,用于修改返回的视图,使其仅最初滚动回到其折叠高度。
  • exitUntilCollapsed : This flag causes the view to be scrolled until it is collapsed (its minHeight is reached) before exiting

    exitUntilCollapsed :此标志导致视图在退出之前一直滚动到其合拢(达到其minHeight)为止
  • snap : Upon a scroll ending, if the view is only partially visible then it will be snapped and scrolled to it’s closest edge. Hence this avoids mid-animation states of a view

    snap :滚动结束后,如果视图仅部分可见,则将对其进行捕捉并滚动到最接近的边缘。 因此,这避免了视图的中期动画状态

TabLayout (TabLayout)

TabLayout is another popular view type introduced in the Material Design Guidelines. It provides a horizontal layout of tabs which are generally placed at the top of the screen according to the Android UI Guidelines.

TabLayout是《材料设计指南》中引入的另一种流行的视图类型。 它提供了选项卡的水平布局,这些选项卡通常根据Android UI准则放置在屏幕顶部。

The following xml snippet depicts how a TabLayout is defined.

以下xml片段描述了如何定义TabLayout。

<android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

The TabLayout consists of two important xml attributes described below:

TabLayout包含两个重要的xml属性,如下所述:

  • app:tabMode – This takes two values:
    • fixed – This displays all the tabs within the screen. Generally used when there are upto 3 tabs
    • scrolling – This lets the user scrolls through the tabs horizontally.

    app:tabMode –这有两个值:
    • 已修复 –在屏幕上显示所有选项卡。 通常在最多3个标签时使用
    • 滚动 –这使用户可以水平滚动选项卡。
  • app:tabGravity – This attribute only works if app:tapMode="fixed". This also takes two values:
    • filled – It’ll distribute the horizontal width across all the tabs
    • center – It’ll display all the tabs in the center horizontal of the screen

    app:tabGravity –仅当app:tapMode="fixed"此属性才有效。 这也有两个值:
    • 填充 –它将在所有标签上分配水平宽度
    • 中心 –它将在屏幕中央水平显示所有选项卡

Note: A TabLayout is generally implemented along with a ViewPager. We’ll implement that in a later tutorial.

注意:TabLayout通常与ViewPager一起实现。 我们将在以后的教程中实现。

Let’s get onto the business logic of our application that hosts a ToolBar and TabLayout inside the AppBarLayout.

让我们进入在AppBarLayout内托管ToolBar和TabLayout的应用程序的业务逻辑。

Android TabLayout AppBarLayout项目结构 (Android TabLayout AppBarLayout Project Structure)

Android TabLayout AppBarLayout示例代码 (Android TabLayout AppBarLayout Example Code)

The activity_main.xml is given below.

下面给出activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.tablayoutappbar.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            android:layout_height="wrap_content"/>

    </android.support.design.widget.AppBarLayout>


    <android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text"/>

    </LinearLayout>

    </android.support.v4.widget.NestedScrollView>


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

In the above code we’ve added a LinearLayout below the AppBarLayout.
Important inferences that need to be drawn are:

在上面的代码中,我们在AppBarLayout下添加了LinearLayout。
需要得出的重要推论是:

  • LinearLayout without the statement app:layout_behavior="@string/appbar_scrolling_view_behavior would overlap the LinearLayout with the AppBarLayout.

    不带语句app:layout_behavior="@string/appbar_scrolling_view_behavior的LinearLayout会将LinearLayout与AppBarLayout重叠。
  • The LinearLayout as a direct child in a CoordinatorLayout won’t scroll. Hence we’ve kept it inside a NestedScrollView

    作为CoordinatorLayout中直接子级的LinearLayout不会滚动。 因此,我们将其保留在NestedScrollView中
  • The TabLayout doesn’t have the layout_scrollFlags. Hence it won’t scroll out of the screen like the ToolBar. We’ll see that shortly.

    TabLayout没有layout_scrollFlags 。 因此,它不会像工具栏一样滚动出屏幕。 我们很快就会看到。

The MainActivity.java is given below

MainActivity.java在下面给出

package com.journaldev.tablayoutappbar;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;


public class MainActivity extends AppCompatActivity {


    TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        tabLayout=(TabLayout)findViewById(R.id.tabs);

        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    }

}

The output of the above application is shown below

上面的应用程序的输出如下所示

Few notable things from the above output are:

以上输出中很少有值得注意的事情是:

  • On scrolling, the status bar scrolls up too thereby leaving the ToolBar in an inconsistent state most of the times

    滚动时,状态栏也会向上滚动,因此大多数时候工具栏都处于不一致状态
  • The Tab Bar indicators have the default color set as the colorAccent

    标签栏指示器将默认颜色设置为colorAccent
  • The default background color of the Tabs is colorPrimary

    选项卡的默认背景颜色是colorPrimary

The first issue is a serious one. To resolve it goto the res->values-21->styles.xml file.
Change the line
@android:color/transparent to
@color/colorPrimaryDark

第一个问题很严重。 要解决该问题,请转到res-> values-21-> styles.xml文件。
换线
@android:color/transparent
@color/colorPrimaryDark

This is how the output should look now:

这是现在输出的样子:

There are numerous ways to customise the TabLayouts. Try calling the setIcon() on the newTab() method instead of setText(). It’ll display the drawable icons. You can even implement both of them like

有许多方法可以自定义TabLayout。 尝试在newTab()方法而不是setText()上调用setIcon()。 它会显示可绘制的图标。 您甚至可以像

tabLayout.addTab(tabLayout.newTab().setText("Speaker Phone").setIcon(android.R.drawable.stat_sys_speakerphone));
        tabLayout.addTab(tabLayout.newTab().setText("Headset").setIcon(android.R.drawable.stat_sys_headset));
        tabLayout.addTab(tabLayout.newTab().setText("Bluetooth").setIcon(android.R.drawable.stat_sys_data_bluetooth));

I ended up with the output below on using the above snippet. What about you?

Android TabLayout AppBarLayout

我使用上面的代码段结束了下面的输出。 你呢?

Besides we can create our own custom styles in the style.xml as shown below.

此外,我们可以在style.xml中创建自己的自定义样式,如下所示。

<style name="MyStyle" parent="Widget.Design.TabLayout">
        <item name="tabIndicatorColor">#FFFF</item>
        <item name="tabIndicatorHeight">5dp</item>
        <item name="tabPaddingStart">8dp</item>
        <item name="tabPaddingEnd">8dp</item>
        <item name="tabBackground">?attr/selectableItemBackground</item>
        <item name="tabSelectedTextColor">#1f2124</item>
    </style>

Let’s add the above style to the respective view in activity_main.xml

让我们将以上样式添加到activity_main.xml中的相应视图中

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            app:tabGravity="fill"
            app:tabMode="fixed"
            style="@style/MyStyle"
            android:layout_height="wrap_content"/>

We’ve ended up with an output like this:

Android TabLayout AppBarLayout

我们最终得到了这样的输出:

You can further style it according to your own needs to enhance the UX of your application.
This brings an end to this tutorial. We’ll be implementing TabLayouts with ViewPager in our next application. You can download the Android TabLayouts Project from the below link

您可以根据自己的需要进一步设置样式,以增强应用程序的用户体验。
本教程到此结束。 我们将在下一个应用程序中使用ViewPager实现TabLayouts。 您可以从以下链接下载Android TabLayouts项目

翻译自: https://www.journaldev.com/12858/android-tablayout-appbarlayout

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值