TabLayout滑動框
阿新 • • 發佈:2018-11-28
加入依賴
implementation 'com.android.support:design:28.0.0'
MainActivity
package com.example.lianxi.activity; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.lianxi.R; import com.example.lianxi.adapter.View_Pager_adapter; public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); tabLayout = findViewById( R.id.tab_layout ); viewPager = findViewById( R.id.view_pager ); viewPager.setAdapter( new View_Pager_adapter(getSupportFragmentManager()) ); tabLayout.setupWithViewPager( viewPager ); } }
介面卡
package com.example.lianxi.adapter; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.example.lianxi.fragment.oneFragment; import com.example.lianxi.fragment.towFragment; public class View_Pager_adapter extends FragmentPagerAdapter { private String[] strings = new String[]{"文章","發現","主題","站點","我的"}; public View_Pager_adapter(FragmentManager fm) { super( fm ); } @Nullable @Override public CharSequence getPageTitle(int position) { return strings[position]; } @Override public Fragment getItem(int i) { switch (i){ case 0: return new oneFragment(); default: return new towFragment(); } } @Override public int getCount() { return strings.length; } }
//佈局
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.MainActivity" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_weight="9" android:layout_width="match_parent" android:background="#ccc" android:layout_height="wrap_content" /> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#dad" android:layout_weight="1" app:tabMode="scrollable" /> </LinearLayout>