Creating Tabs Correctly on Android Currently

4

I'm trying to implement in the application that I'm creating Tabs, like this:

But when I try to implement, I'm always faced with deprecated classes and methods, such as TabListener , ActionBarActivity and now I'm not sure how to create it, I do not know the correct way to create and I already researched the internet for examples but it is full of examples using these obsolete classes and methods.

I need it to work on older versions of the SDK, the smaller the better version.

Thank you in advance.

    
asked by anonymous 03.09.2015 / 01:43

1 answer

7

The best way to implement a tab-based layout is to use TabLayout of design library .

Unfortunately it requires you to have the trio in your dependency group:

compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:support-v4:23.0.0'
compile 'com.android.support:design:23.0.0'

But nowadays, if you want to make an app that has good compatibility without much effort and adds some elements of Material Design, you can not get away from it.

The basics to implement are:

Basic Layout

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" />
</LinearLayout>

Setup in your Activity

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(...);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

That's the basics. When you start to combine AppBarLayout + CoordinatorLayout + Toolbar + some component with NestedScroll you can have many variations that get very good.

A good source to see the possibilities: link and link

Source: link

    
03.09.2015 / 01:59