如何在 android 中制作离散的 seek/progress 栏?

How to make discrete seek/progress bar in android?

如何制作像 android 中的步进器一样的离散 progress/seek 条形图。就像我们在 whatsapp 状态故事中看到的那样。

虽然很多库都实现了,但我需要在不使用库的情况下实现它。

我在水平线性布局中使用视图,并根据需要显示的部分数量或状态故事数量对其进行动态划分。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

<LinearLayout
    android:id="@+id/layout_views"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:orientation="horizontal"
    android:padding="4dp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:text="Click" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
Button mButton;
int x=0,height,width,numberOfSections;
LinearLayout layoutViews;
ArrayList<View> viewsList =new ArrayList<>();

@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //findviews
    layoutViews = findViewById(R.id.layout_views);
    mButton = (Button) findViewById(R.id.button);

    //for getting dimensions of screen
    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;

    //suppose we have to cut section into 4 parts
    numberOfSections = 10;
    width -= (16 + 16*numberOfSections);    //reducing length of layout by 16dp from left and right and in between 16dp {in between*number of sections)
    width /= numberOfSections;
    for(int i=0;i<numberOfSections;i++){
        View v = new View(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, 10);
        params.setMargins(16,0,0,0);    //giving 16dp internal margin between two views
        v.setLayoutParams(params);
        viewsList.add(v);   //adding views in array list for changing color on click of button

        v.setBackgroundColor(getResources().getColor(colorAccent));
        layoutViews.addView(v);
    }
    //button onclick function
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                buttonClick();
        }
    });
}

public void buttonClick(){
   viewsList.get(x).setBackgroundColor(getResources().getColor(colorPrimaryDark));
   x++;
  }
 }

Voyella!你制作了这个动态的故事进度条,虽然你可以在视图中添加过渡动画。