效果图:
1
文件:
导包:
compile 'com.android.support:design:26+'
activity_main.xml
RelativeLayout布局
<android.support.design.widget.TabLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:id="@+id/tas"app:tabGravity="center"app:tabIndicatorColor="@color/colorAccent"app:tabMode="scrollable"app:tabSelectedTextColor="@color/colorPrimaryDark"app:tabTextColor="@color/colorPrimary"></android.support.design.widget.TabLayout><android.support.v4.view.ViewPagerandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/vp"android:layout_below="@+id/tas"></android.support.v4.view.ViewPager>
item.xml
<TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tv"android:textColor="#f00"/>
MainActivity.java
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.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;public class MainActivity extends AppCompatActivity {private List<String> datas = new ArrayList<String>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TabLayout tabLayout = (TabLayout) findViewById(R.id.tas);ViewPager viewPager = (ViewPager) findViewById(R.id.vp);datas.add("推荐");datas.add("要闻");datas.add("娱乐");datas.add("科技");datas.add("汽车");datas.add("体育");datas.add("图片");datas.add("动漫");datas.add("社会");datas.add("游戏");
// tabLayout.addTab();viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));//进行关联tabLayout.setupWithViewPager(viewPager);}class MyAdapter extends FragmentPagerAdapter {//带参的构造方法public MyAdapter(FragmentManager fm) {super(fm);}//返回选项卡的文本 ,,,添加选项卡@Overridepublic CharSequence getPageTitle(int position) {return datas.get(position);}@Overridepublic Fragment getItem(int position) {Log.d("zzz", "position:" + position);//创建fragment对象并返回Bundle bundle = new Bundle();bundle.putString("key", datas.get(position));Fragment01 fragment01 = new Fragment01();fragment01.setArguments(bundle);return fragment01;}@Overridepublic int getCount() {return datas.size();//返回选项卡的数量}}
}
Fragment01.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;public class Fragment01 extends Fragment {@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = View.inflate(getActivity(), R.layout.item, null);TextView textView = (TextView) view.findViewById(R.id.tv);Bundle bundle = getArguments();textView.setText(bundle.getString("key"));return view;}
}