按钮内的圆形进度指示器,Android Material 设计

Circular Progress Indicator inside Buttons, Android Material design

我刚刚读到 Material 设计中的按钮 (MaterialButton) (progress indicator material design) 能够容纳一个圆形进度指示器,如您在附件中所见图片

基本上当您按下按钮时删除文本并显示进度指示器,但没有关于如何实现它的线索,有人已经处理了吗?

非常感谢任何提示。谢谢

实现此目的的方法之一是创建一个布局,您将在其中放置一个容器并放置按钮和 CircularProgressIndicator

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/some_height"
        android:background="#00000000"
        android:layout_marginRight="@dimen/margin_right"
        android:layout_marginLeft="@dimen/margin_left">

        <Button
            android:id="@+id/btn_download"
            android:layout_width="match_parent"
            android:layout_height="@dimen/some_height"
            android:text="Download"
            android:layout_gravity="center"
            android:visibility="visible"
            android:textColor="#FFFFFF"/>

     
    <com.google.android.material.progressindicator.CircularProgressIndicator
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </FrameLayout>

然后您只需切换进度条的可见性并删除文本。

另一种方法是使用自定义 animation drawable。然后,您可以将其作为 drawableStartdrawableEnd 添加到您的按钮中,并带有一些定位,甚至可能作为背景。

第三个选项是:

顺便说一句,在上面的 xml 代码中,您可以将 Button 替换为 MaterialButton

借助 MaterialComponents 库,您可以使用 IndeterminateDrawable class 创建一个 CircularProgressIndicator 并将其应用于 ButtonButton:

中的图标
   val spec =
        CircularProgressIndicatorSpec(this,  /*attrs=*/null, 0,
            com.google.android.material.R.style.Widget_Material3_CircularProgressIndicator_ExtraSmall)
    val progressIndicatorDrawable =
        IndeterminateDrawable.createCircularDrawable(this, spec)
    //...
    button.setOnClickListener {
        button.icon = progressIndicatorDrawable
    }

有:

<com.google.android.material.button.MaterialButton
    android:id="@+id/indicator_button"
    style="@style/Widget.Material3.Button.OutlinedButton.Icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:text="Button"/>

使用 Compose 你可以使用类似的东西:

 var progressIndicatorVisible by remember { mutableStateOf(false) }

 Button(
   onClick = {
     scope.launch {
         progressIndicatorVisible = true

         // Just for example
         delay(5000)
         progressIndicatorVisible = false
     }
   }, 
   modifier = Modifier.animateContentSize()){

     if (progressIndicatorVisible) {
         CircularProgressIndicator(
             color = White,
             strokeWidth = 2.dp,
             modifier = Modifier.size(15.dp)
         )
     }
     Text (
         "Button",
         modifier = Modifier.padding(start = if (progressIndicatorVisible) 8.dp else 0.dp)
     )
 }