Tabレイアウト

#コピペでサクッとTabLayout

![device-2016-02-29-190202.png](https://qiita-image-store.s3.amazonaws.com/0/99731/f54082d7-7c17-490e-cef7-76ed4d445862.png)

![device-2016-02-29-190213.png](https://qiita-image-store.s3.amazonaws.com/0/99731/856eb036-2339-3617-8a82-931cc0f876ac.png)


## compile 'com.android.support:design:23.1.1'追加

```xml
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}
```

```java:MainActivity.java

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements OnSampleListChangeListener {
    CustomAdapter adapter;
    ViewPager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        //pager.setOffscreenPageLimit(3);//タブ３つは破棄せず再利用
        adapter = new CustomAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        tabLayout.setupWithViewPager(pager); //スワイプするとタブのステータスが変更
    }
    @Override public void onListSelectedChanged(String s) {
        TextFragment fragment = (TextFragment)adapter.findFragmentByPosition(pager, 1);
        fragment.setText(s);
        pager.setCurrentItem(1);

    }
    public class CustomAdapter extends FragmentPagerAdapter {

        private String[] pageTitle = { "Page1", "Page2"};//タブのタイトル

        public CustomAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new MyListFragment();
                case 1:
                    return TextFragment.newInstance(1);
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return pageTitle.length;//タブ数
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return pageTitle[position]; //タブのタイトル
        }

        public Fragment findFragmentByPosition(ViewPager viewPager,
                                               int position) {
            return (Fragment) instantiateItem(viewPager, position);
        }
    }
    public static class TextFragment extends Fragment {

        private static final String ARG_POSITION = "position";

        private TextView title_tv;

        public static TextFragment newInstance(int position) {
            TextFragment fragment = new TextFragment();

            Bundle args = new Bundle();
            args.putInt(ARG_POSITION, position);
            fragment.setArguments(args);
            return fragment;
        }

        public void setText(String s){
            title_tv.setText(s);
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putString("txt", title_tv.getText().toString());
        }

        @Override
        public View onCreateView(LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {

            int page = getArguments().getInt(ARG_POSITION, 0);
            View view = inflater.inflate(R.layout.fragment_main, container, false);
            title_tv = (TextView)view.findViewById(R.id.page_text);
            if (savedInstanceState != null) {
                String str = savedInstanceState.getString("txt");
                if (str != null) {
                    title_tv.setText(str);
                }
            }

            return view;
        }
    }

    public static class MyListFragment extends ListFragment {

        private ArrayAdapter<ListItem> adapter;
        private List<ListItem> list;

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            list = new ArrayList<ListItem>();
            for(int i = 0;  i < 90; i++) {
                ListItem item = new ListItem();
                item.set("No" + i);
                list.add(item);
            }
            adapter = new ListAdapter(getActivity(), list);
            setListAdapter(adapter);

            getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ListView listView = (ListView) parent;
                    ListItem item = (ListItem) listView.getItemAtPosition(position);
                    Toast.makeText(getActivity(), item.get(), Toast.LENGTH_SHORT).show();
                    if(getActivity() instanceof OnSampleListChangeListener){
                        OnSampleListChangeListener listener = (OnSampleListChangeListener) getActivity();
                        listener.onListSelectedChanged(item.get());
                    }
                }
            });
        }


        private class ListAdapter extends ArrayAdapter<ListItem> {
            private LayoutInflater mInflater;

            public ListAdapter(Context context, List<ListItem> objects) {
                super(context, 0, objects);
                mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            public View getView(int position, View convertView, ViewGroup parent) {

                //キャッシュ
                final ViewHolder holder;

                //初めて
                if (convertView == null) {

                    //動的にレイアウトファイルを利用
                    convertView = mInflater.inflate(R.layout.list_row, parent, false);

                    //キャッシュ
                    holder = new ViewHolder();
                    holder.tvListText = (TextView)convertView.findViewById(R.id.list_text);

                    //次回からViewHolderを利用
                    convertView.setTag(holder);

                } else {
                    holder = (ViewHolder)convertView.getTag();
                }

                final ListItem item = getItem(position);
                holder.tvListText.setText(item.get());
                return convertView;
            }
        }

        //キャッシュ
        private class ViewHolder {
            TextView tvListText;
        }

        private class ListItem {
            private String listText = "";
            public void set(String listText) {
                this.listText = listText;
            }
            public String get() {
                return this.listText;
            }
        }
    }
}

```


```xml:layout/fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/page_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="32sp" />
</RelativeLayout>
```

#リストの行レイアウト
```xml:layout/list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >"

    <TextView
        android:id="@+id/list_text"
        android:padding="10dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:layout_weight="1"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
```

```xml:activity_main.xml
<RelativeLayout
    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.support.design.widget.TabLayout
        android:id="@+id/tabs"
        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="wrap_content"
        android:layout_below="@id/tabs"
        />

</RelativeLayout>
```

```java:OnSampleListChangeListener.java
public interface OnSampleListChangeListener {
    void onListSelectedChanged(String s);
}
```