android/195739.html">TabLayou 主要实现的是标题头的 滑动 这个 控件 类似于 ScrollView

XML中的布局

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"

>

android:id="@+id/homefragment_tablelayouts"

android:layout_width="0dp"

android:layout_height="30dp"

app:tabIndicatorHeight="2dp"

android:layout_weight="1"

app:tabIndicatorColor="@color/colorred"

app:tabSelectedTextColor="#000000"

app:tabMode="scrollable"

>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/add_channel_titlbar_new"

/>

android:layout_weight="1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/homefragment_vp"

>

以下是代码的实现

//定义一个方法

public void getVpTitleData() {

// 找到 TabLayou 控件

TabLayout mTabLayout= (TabLayout) getView().findViewById(R.id.homefragment_tablelayouts);

// 找到 ViewPager 控件

ViewPager mViewPager= (ViewPager) getView().findViewById(R.id.homefragment_vp);

//定义 title 集合 来存储 解析的data数据

listtitle = new ArrayList<>();

listtitle .add("头条");

listtitle .add("社会");

listtitle .add("国内");

listtitle .add("国际");

listtitle .add("明星");

listtitle .add("娱乐");

listtitle .add("军事");

listtitle .add("财经");

listtitle .add("时尚");

listtitle .add("八卦");

//遍历 listtitle 集合 将title 添加经 TabLayou z中

for (int i = 0; i

mTabLayout.addTab(mTabLayout.newTab().setText(listtitle.get(i)));

}

//创建集合 循环添加创建的Fragment

listfragment = new ArrayList<>();

for (int i = 0; i

BeiJingFragment mjingFragment = new BeiJingFragment();

listfragment.add(mjingFragment);

}

HomeFragmentVPFragmentAdapter mAdapter = new HomeFragmentVPFragmentAdapter(getFragmentManager(),listfragment,listtitle);

//给ViewPager设置适配器

mViewPager.setAdapter(mAdapter);

//将TabLayout和ViewPager关联起来。

mTabLayout.setupWithViewPager(mViewPager);

//给TabLayout设置适配器

mTabLayout.setTabsFromPagerAdapter(mAdapter);

}

ViewPafer与Fragment的适配器

public class HomeFragmentVPFragmentAdapter extends FragmentStatePagerAdapter {

List listfragment;

List listtitle;

public HomeFragmentVPFragmentAdapter(FragmentManager fm, List listfragment, List listtitle) {

super(fm);

this.listfragment = listfragment;

this.listtitle = listtitle;

}

@Override

public CharSequence getPageTitle(int position) {

return listtitle.get(position);

}

@Override

public Fragment getItem(int position) {

return listfragment.get(position);

}

@Override

public int getCount() {

return listfragment.size();

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐