Android开发教程viewpager2点击指示标也能切换
viewpager2的使用范例,关键是点击指示标也能切换
一、思路:
用viewpager2加两个imageview
二、效果图:
三、关键代码:
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager2;
//private SlidingTabLayout stl_title;
private ImageView iv1;
private ImageView iv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewpager2);
iv1 = findViewById(R.id.iv1);
iv2 = findViewById(R.id.iv2);
//stl_title = findViewById(R.id.stl_title);
FragmentStateAdapter fragmentStateAdapter = new FragmentStateAdapter(this) {
@NonNull
@Override
public Fragment createFragment(int position) {
return new CatalogFragment(position);
}
@Override
public int getItemCount() {
return 2;
}
};
viewPager2.setAdapter(fragmentStateAdapter);
iv1.setBackgroundColor(Color.RED);
iv2.setBackgroundColor(Color.parseColor("#eeeeee"));
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
if (position == 0){
iv1.setBackgroundColor(Color.RED);
iv2.setBackgroundColor(Color.parseColor("#eeeeee"));
} else {
iv2.setBackgroundColor(Color.RED);
iv1.setBackgroundColor(Color.parseColor("#eeeeee"));
}
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewPager2.setCurrentItem(0);
}
});
iv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewPager2.setCurrentItem(1);
}
});
// ArrayList<String> arrayListTitle = new ArrayList<>();
// arrayListTitle.add("京东1");
// arrayListTitle.add("京东2");
// stl_title.setViewPager2(viewPager2, arrayListTitle);
}
}
四、项目demo源码结构图:
有问题或者需要完整源码的私信我