tablelayout_demo2

来源:互联网 发布:双源abo乐乎 编辑:程序博客网 时间:2024/06/08 05:05

注释:
代码实现 Tablayout+viewpage 并向viewpage中传入 Tab的值

mian方法:
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("游戏"); //设置加载页数   // viewPager.setOffscreenPageLimit(list.size());    viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));    //进行关联    tabLayout.setupWithViewPager(viewPager);}class MyAdapter extends FragmentPagerAdapter{    //带参的构造方法    public MyAdapter(FragmentManager fm) {        super(fm);    }    //返回选项卡的文本 ,,,添加选项卡    @Override    public CharSequence getPageTitle(int position) {        return datas.get(position);    }    @Override    public Fragment getItem(int position) {        Log.d("zzz","position:"+position);        //创建fragment对象并返回        Bundle bundle=new Bundle();        bundle.putString("key",datas.get(position));        ContentFragment contentFragment=new ContentFragment();        contentFragment.setArguments(bundle);        return contentFragment;    }    @Override    public int getCount() {        return datas.size();//返回选项卡的数量    }}

}

ContentFragment.java类
public class ContentFragment extends Fragment {

@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    View view=View.inflate(getActivity(),R.layout.content,null);    TextView textView= (TextView) view.findViewById(R.id.tv);    Bundle bundle=getArguments();    textView.setText(bundle.getString("key"));    return view;}

}

视图:

 <android.support.design.widget.TabLayout        android: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.ViewPager        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/vp"        android:layout_below="@+id/tas"        ></android.support.v4.view.ViewPager>

//content.xml

    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/tv"        android:textColor="#f00"/>