package com.example.day007;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import com.example.day007.adapter.MyFragmentAdapter;
import com.example.day007.fragment.OneFragment;
import com.example.day007.fragment.TwoFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TabLayout tabId;
private ViewPager vpId;
private List<Fragment> list = new ArrayList<>();
private List<String> titles = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
tabId = findViewById(R.id.tab_id);
vpId = findViewById(R.id.vp_id);
list.add(new OneFragment());
list.add(new TwoFragment());
list.add(new OneFragment());
list.add(new TwoFragment());
titles.add("视频");
titles.add("新闻");
titles.add("图片");
titles.add("留言");
MyFragmentAdapter myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(), list, titles);
vpId.setAdapter(myFragmentAdapter);
//把viewPager和tabLayout绑定在一起,注释掉看看效果.
tabId.setupWithViewPager(vpId);
}
}
package com.example.day007.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 android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.ArrayList;
import java.util.List;
/**
-
${FENG}
-
2019-07-11
*/
public class MyFragmentAdapter extends FragmentStatePagerAdapter {
private List list;
private List titles;public MyFragmentAdapter(FragmentManager fm, List list, List titles) {
super(fm);
this.list = list;
this.titles = titles;
}@Override
public int getCount() {
return list.size();
}@Override
public Fragment getItem(int i) {
return list.get(i);
}//返回与viewpage关联以后的tablayot的内容
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
/** -
A simple {@link Fragment} subclass.
*/
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}