How to make tabs similar to WhatsApp?

3

Someone has some examples of how I can create this style of tabs on Android.

In the image the example is from Whats App.

I mean:

1 - as abas CALL, Chats, Contacts
2 - The Search bar, which always stays, regardless of the tab I click

Can anyone help me?

    
asked by anonymous 12.07.2016 / 12:14

1 answer

7

In the case of WhatsApp I imagine a TabLayout and a ViewPager to be used:

XML:

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

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

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

FragmentPagerAdapter:

public class MyCustomPagerAdapter extends FragmentPagerAdapter {
    public MyCustomPagerAdapter(FragmentManager fm) {
        super(fm);
    }

//   Aqui você retorna uma instancia de fragment para cada aba dependendo da posição
    @Override
    public Fragment getItem(int position) {
//  Exemplo:
        switch (position) {
            case 0: return new CallFragment();
            case 1: return new ChatFragment();
        }
        return null;
    }

//   Aqui você retorna o número de páginas que o pager vai ter 
    @Override
    public int getCount() {
//  Exemplo   
        return 2;
    }

//  Aqui você retorna o titulo de acordo com a posição de cada aba (as que você definiu antes no getItem)  
    @Override
    public CharSequence getPageTitle(int position) {
//  Exemplo
        switch (position) {
            case 0: return "Calls";
            case 1: return "Chats";
        }
        return super.getPageTitle(position);
    }
}

Activity

public class MyActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.my_pager_layouut);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        ViewPager pager = (ViewPager) findViewById(R.id.pager);
        MyCustomPagerAdapter pagerAdapter = new MyCustomPagerAdapter(getFragmentManager());
        pager.setAdapter(pagerAdapter);
        tabLayout.setupWithPager(pager);
    }
}
    
12.07.2016 / 12:52