如何在 Android 中创建中间带有图标的按钮?

How do I create button with an icon in the center in Android?

我应该创建一个按钮,按钮中央的图标位于文本旁边,如下所示:

这是我想出的解决方案:

<androidx.cardview.widget.CardView
    android:layout_width="0dp"
    android:layout_height="75dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:backgroundTint="@color/tomato"
    app:cardCornerRadius="70dp"

    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintWidth_percent="0.9">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="20dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:layout_marginRight="10dp"
                android:src="@drawable/ic_baseline_shopping_cart_24" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add This To Cart"
                android:textColor="@color/white"
                android:textSize="25dp" />
        </LinearLayout>
    </RelativeLayout>
</androidx.cardview.widget.CardView>

但我认为它很难编码。所以,我的问题是:是否有更好的设计方法或用于设计它的库?

您可能应该开始使用 Material Components library,它带有大量预构建的现代组件,以防止您必须自己实现此类琐碎的事情。

然后可以使用MaterialButton并设置图标属性:

<com.google.android.material.button.MaterialButton
    app:icon="@drawable/..." />

您可以查看特定的 documentation 以了解有关样式等的信息。

删除你的 ImageView 然后 在 TextView

中写下这一行

android:drawableLeft="@drawable/ic_baseline_shopping_cart_24"

在你的代码中。

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add This To Cart"
android:textColor="@color/white"
android:textSize="25dp" 
androidd:drawableLeft="@drawable/ic_baseline_shopping_cart_24/>

您可以使用 MaterialButton:

   <com.google.android.material.button.MaterialButton
       app:icon="@drawable/ic_add_24px"
       app:iconPadding="0dp"
       app:iconGravity="textStart"
       app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.rounded50"
       ../>

与:

<style name="ShapeAppearanceOverlay.App.rounded50" parent="">
    <item name="cornerSize">50%</item>
</style>