使用 androidx 在 Viewpager 中进行圆点设计

Dots design in Viewpager with androidx

应用此 link 的解决方案 Android ViewPager with bottom dots 我发现在 androidx 中,实现 "com.google.android.material:material:1.0.0" 我无法调整点的宽度,也无法调整点与点之间的边距

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<!-- activity_screen_slide.xml -->
<androidx.viewpager.widget.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/viewPagerDots"
        app:tabIndicatorFullWidth="false"
        app:tabPaddingStart="16dp"
        app:tabPaddingEnd="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabBackground="@drawable/tab_dot_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp" />
</RelativeLayout>

drawable/viewpager_dot_indicator_default.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >

    <solid
        android:color="@color/colorPrimary" />
</shape>

drawable/viewpager_dot_indicator_selected.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:height="160dp"
        android:width="160dp"/>
  <solid
        android:color="@color/red" />
</shape>

This is what i want

this is what i have

如果您想在 viewpager 中添加点,我建议您使用此代码。 它会根据您的选择为您提供完美的点。

首先为点创建一个线性布局并将其方向设置为水平。

然后在你的Java文件中声明textview数组

TextView[] setDots;

现在添加以下代码片段。

private void addDots(int position){

    setDots = new TextView[3]; // No. of dots. Here you'll get three dots.
    dots.removeAllViews();

    for (int i = 0; i<setDots.length; i++){
        setDots[i] = new TextView(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            setDots[i].setText(HtmlCompat.fromHtml("&#8226;", HtmlCompat.FROM_HTML_MODE_LEGACY));
        }
        setDots[i].setTextSize(35); //Dots size.

        dots.addView(setDots[i]);
    }

    if (setDots.length > 0){
        setDots[position].setTextColor(getResources().getColor(R.color.colorPrimaryDark, getTheme())); //Change the color as your need.
    }
}

然后在ViewPager.OnPageChangedListener里面加上点。

 @Override
 public void onPageSelected(int position) {
            addDots(position);
 }