TabLayout+ViewPage建立关联setupWithViewPager()出现的问题
Posted 一如年少模样
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TabLayout+ViewPage建立关联setupWithViewPager()出现的问题相关的知识,希望对你有一定的参考价值。
xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.study.yxrr.tablayoutviewpage.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/id_tablayout"
android:layout_width="match_parent"
android:layout_height="50dip" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:id="@+id/id_vp"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
代码:
public class MainActivity extends AppCompatActivity
private TabLayout mTl;
private ViewPager mVp;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
private void initView()
mTl = (TabLayout) findViewById(R.id.id_tablayout);
mVp = (ViewPager) findViewById(R.id.id_vp);
//添加两个tab
mTl.addTab(mTl.newTab().setText("NBA"));
mTl.addTab(mTl.newTab().setText("阅读"));
mTl.addTab(mTl.newTab().setText("健康"));
//让tablayout与viewpager建立关联关系
mTl.setupWithViewPager(mVp);
mVp.setAdapter(new PagerAdapter()
@Override
public int getCount()
return 3;
@Override
public boolean isViewFromObject(View view, Object object)
return view == object;
@Override
public Object instantiateItem(ViewGroup container, int position)
TextView textView = new TextView(container.getContext());
textView.setText("position:" + position);
container.addView(textView);
return textView;
@Override
public void destroyItem(ViewGroup container, int position, Object object)
container.removeView((View) object);
@Override
public CharSequence getPageTitle(int position)
if(position ==0)
return "NBA";
else if (position==1)
return "阅读";
else
return "健康";
);
代码中 我们给TabLayout添加了三个,如果我们补充协议getPageTitle方法是不会出现的,这个原因是因为tablayout与viewpager建立关联关系的时候,已经把tab全部remove了
源码如下:
以上是关于TabLayout+ViewPage建立关联setupWithViewPager()出现的问题的主要内容,如果未能解决你的问题,请参考以下文章