要在ViewPager中添加頁(yè)碼指示器,你可以使用一個(gè)現(xiàn)成的庫(kù)或者自定義一個(gè)簡(jiǎn)單的指示器。以下是一些示例代碼:
使用現(xiàn)成的庫(kù):
implementation 'me.relex:circleindicator:2.1.4'
<me.relex.circleindicator.CircleIndicator
android:id="@+id/indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"/>
CircleIndicator indicator = findViewById(R.id.indicator);
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(new MyPagerAdapter());
indicator.setViewPager(viewPager);
自定義簡(jiǎn)單的指示器:
<LinearLayout
android:id="@+id/indicatorContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal"/>
LinearLayout indicatorContainer = findViewById(R.id.indicatorContainer);
for (int i = 0; i < numPages; i++) {
ImageView indicator = new ImageView(this);
indicator.setImageResource(R.drawable.ic_indicator);
indicator.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
indicatorContainer.addView(indicator);
}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
ImageView indicator = (ImageView) indicatorContainer.getChildAt(i);
indicator.setImageResource(i == position ? R.drawable.ic_selected_indicator : R.drawable.ic_indicator);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
這樣就可以在ViewPager中添加頁(yè)碼指示器了。你可以根據(jù)自己的需求選擇使用現(xiàn)成的庫(kù)還是自定義一個(gè)簡(jiǎn)單的指示器。