1. 程式人生 > >TabLayout橫向滾動

TabLayout橫向滾動

依賴:

compile 'com.android.support:design:26.0.0-alpha1'

佈局:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

    <android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height=
"wrap_content" android:background="#e5e2e2" app:tabIndicatorColor="#20b3a2" app:tabIndicatorHeight="4dp" app:tabSelectedTextColor="#ff0000" app:tabGravity="fill" app:tabTextColor="#aaa" /> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height=
"match_parent" /> </LinearLayout>
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import 
java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private TabLayout tab; private ViewPager pa; List<String> lists=new ArrayList<String>(); List<Fragment>list2=new ArrayList<Fragment>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tab = (TabLayout)findViewById(R.id.tab); pa = (ViewPager)findViewById(R.id.pager); lists.add("ANDROID"); lists.add("IOS"); lists.add("福利"); list2.add(new AnFragment()); list2.add(new IOSFragment()); list2.add(new FuFragment()); //tablayoutviewpager關聯 tab.setupWithViewPager(pa); //設定viewpager介面卡 pa.setAdapter(new FragmentPagerAdapter(MainActivity.this.getSupportFragmentManager()) { //重寫這個方法,將設定每個Tab的標題 @Override public CharSequence getPageTitle(int position) { return lists.get(position); } @Override public int getCount() { return list2.size(); } @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); if (lists.get(position).equals("ANDROID")){ bundle.putString("name","ANDROID"); }else if (lists.get(position).equals("IOS")){ bundle.putString("name","IOS"); }else if (lists.get(position).equals("福利")){ bundle.putString("name","福利"); } list2.get(position).setArguments(bundle); return list2.get(position); } }); } }

fragment中寫:

 
public class AnFragment extends Fragment  {


    private View view;

    @Nullable
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.layout_android, container, false);
        Bundle bundle = getArguments();
        //接收傳遞過來的值
String string = bundle.getString("name", "ANDROID");
        return view;
    }
}