Как установить Android-панель TabLayout в нижней части экрана?

Это мой первый раз на Stack Over, поэтому, пожалуйста, со мной. Мой вопрос заключается в том, как я могу настроить новый вкладка TabLayout для дизайна Android в нижней части экрана, наподобие нижней панели инструментов Instagram.

Если вы никогда не видели Instagram UI, вот скриншот:

If you have never seen Instagram's UI here is a screenshot of it. Если есть лучший способ приблизиться к этому, пожалуйста, не стесняйтесь публиковать его здесь (с возможным примером кода), я буду очень благодарен.

Вот мой код: activity_main.xml

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.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"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

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

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

Я пробовал много методов и обходных решений, предложенных сообществом Stack Overflow, но никто не работает с этой новой реализацией вкладок в android. Я знаю, что этот дизайн пользовательского интерфейса не соответствует правилам проектирования Android, поэтому, пожалуйста, не комментируйте его. Этот дизайн пользовательского интерфейса имеет жизненно важное значение для моего приложения UX, и я был бы признателен за получение ответа на него. Спасибо!

Ответы

Ответ 1

Я считаю, что у меня есть самое простое исправление. Используйте LinearLayout и установите высоту для viewpager равным 0dp с layout_weight = "1". Убедитесь, что LinearLayout имеет ориентацию по вертикали и что просмотрщик приходит перед TabLayout. Вот как выглядят мины:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <include layout="@layout/toolbar" android:id="@+id/main_toolbar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        />

</LinearLayout>

И в качестве бонуса вы должны создать свою панель инструментов только один раз как toolbar.xml. Таким образом, все, что вам нужно сделать, это использовать тег include. Делает ваш макет более чистым. Наслаждайтесь!

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

Обновление 11.2.2016: Для тех из вас, кто не знает, как надуть панель инструментов, вот как это сделать. Убедитесь, что ваша активность расширяет AppCompatActivity, поэтому вы можете вызвать setSupportActionBar() и getSupportActionBar().

Toolbar mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Ответ 2

Лучше разделите как AppBarLayout, так и tabLayout, как мой код ниже. Таким образом вы можете изменять панель вкладок и просматривать свойства пейджера независимо.

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.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"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.AppBarLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:layout_above="@+id/tabs"/>

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

Ответ 3

У меня была такая же проблема на Android Studio 2.2. Это то, что я сделал,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:subtitleTextColor="@color/color_white"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="@string/call_log"
        app:titleTextColor="@color/color_white"
        />

    <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/tabLayout" />

        <android.support.design.widget.TabLayout
            android:layout_alignParentBottom="true"
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"/>
    </RelativeLayout>

</LinearLayout>

Ответ 4

вы можете попробовать Добавление представления нижней навигации в макет Для начала нам нужно обновить нашу зависимость!

compile ‘com.android.support:design:25.0.0’

и

[![<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Content Container -->
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="@color/colorPrimary"
app:itemIconTint="@color/white"
app:itemTextColor="@color/white"
app:menu="@menu/bottom_navigation_main" />
</RelativeLayout>][1]][1]

bottom navigation view

youtube использует это нижнее навигационное представление

для получения дополнительной информации вы можете посмотреть этот учебник https://www.learn2crack.com/2017/06/android-using-bottomnavigationview.html

Ответ 5

Замените код TabLayout этим

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