1. 程式人生 > >橫向滑動Tablayout

橫向滑動Tablayout

橫向滑動只需要在佈局用Tablyout控制元件

在此之前在build.gradle裡面新增

compile 'com.android.support:design:25.0.1'

下面是佈局檔案

<android.support.design.widget.TabLayout
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#f00"
app:tabMode="scrollable"
app:tabSelectedTextColor=
"#f0f9"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v4.view.ViewPager>

主頁程式碼

public class MainActivity extends AppCompatActivity {

    private 
TabLayout tb; private ViewPager viewp; String[] title = new String[]{"初學者", "演員", "認真的雪", "火星人來過", "聽說", "我好像在哪見過你", "方圓幾裡", "紳士"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tb
= (TabLayout) findViewById(R.id.tb); viewp = (ViewPager) findViewById(R.id.vp); //預設選中第一個 tb.addTab(tb.newTab().setText(title[0]), true); addtab(); tb.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewp.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return title.length; } @Override public Fragment getItem(int position) { return Fragment.getInstance(title[position]); } }); viewp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { tb.getTabAt(position).select(); } @Override public void onPageScrollStateChanged(int state) { } }); } private void addtab() { for (int i = 1; i < title.length; i++) { tb.addTab(tb.newTab().setText(title[i]), false); } } }
ViewPage的setAdapter裡面Fragment.getInstance(title[position])傳值到Fragment

需要建立一個Fargment

public class Fragment extends android.support.v4.app.Fragment {

    @Nullable
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView tv = new TextView(getActivity());
        tv.setText(getArguments().getString("title"));
        return tv;

    }

    public static Fragment getInstance(String title) {
        Fragment fragment = new Fragment();
        Bundle args = new Bundle();
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }
}