Android 如何以编程方式更改轮廓按钮图标?

Android 如何以编程方式更改轮廓按钮图标?,android,button,material-design,Android,Button,Material Design,从这个参考有一个设置图标的方法,但我如何才能达到它? 如果您没有使用material主题作为应用程序主题,则需要在xml中声明material按钮,如下所示: <com.google.android.material.button.MaterialButton android:id="@+id/outlinedButton" android:layout_width="wrap_content

从这个参考有一个设置图标的方法,但我如何才能达到它?


如果您没有使用material主题作为应用程序主题,则需要在xml中声明material按钮,如下所示:

 <com.google.android.material.button.MaterialButton
                android:id="@+id/outlinedButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Outlined button"
                app:icon="@drawable/ic_launcher_background"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon"
                />

要以编程方式更改图标,请执行以下操作:

findViewById<MaterialButton>(R.id.outlinedButton).setIcon(ContextCompat.getDrawable(this,R.drawable.ic_launcher_foreground))
findViewById(R.id.outlinedButton).setIcon(ContextCompat.getDrawable(this,R.drawable.ic\u launcher\u前台))

如果您不使用material主题作为应用程序主题,则需要在xml中声明material按钮,如下所示:

 <com.google.android.material.button.MaterialButton
                android:id="@+id/outlinedButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Outlined button"
                app:icon="@drawable/ic_launcher_background"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon"
                />

要以编程方式更改图标,请执行以下操作:

findViewById<MaterialButton>(R.id.outlinedButton).setIcon(ContextCompat.getDrawable(this,R.drawable.ic_launcher_foreground))
findViewById(R.id.outlinedButton).setIcon(ContextCompat.getDrawable(this,R.drawable.ic\u launcher\u前台))

在Android中,每个UI小部件组件要么是一个,要么来自
视图
,并且根据文档,从
文本视图
派生

现在有一些关于Android中文本的重要信息需要了解。该框架允许您为每个文本定义
复合绘图表
——请看一看。有了它,您可以通过编程方式设置复合可绘图项,但还要注意文档中的
相关XML属性部分-可绘图项可以用XML定义,这通常是最简单的方法(当然,如果适用于给定的情况)

您附加的按钮图像看起来也是一个标准的
按钮
,因此“plus”图标应该是一个可绘制的复合图标,因此应该易于更改,如上所述


编辑:再想一想,谷歌的安卓材料设计库并不是那个么简单。看看我上面链接的
MaterialButton
docs,这里有一个方法,它可能回答了您的问题。您还可以使用
app:icon
属性定义可在XML中绘制的图标。

在Android中,每个UI小部件组件要么是一个,要么来自
视图
,根据文档,从
文本视图
派生

现在有一些关于Android中文本的重要信息需要了解。该框架允许您为每个文本定义
复合绘图表
——请看一看。有了它,您可以通过编程方式设置复合可绘图项,但还要注意文档中的
相关XML属性部分-可绘图项可以用XML定义,这通常是最简单的方法(当然,如果适用于给定的情况)

您附加的按钮图像看起来也是一个标准的
按钮
,因此“plus”图标应该是一个可绘制的复合图标,因此应该易于更改,如上所述


编辑:再想一想,谷歌的安卓材料设计库并不是那个么简单。看看我上面链接的
MaterialButton
docs,这里有一个方法,它可能回答了您的问题。您还可以使用
app:icon
属性定义可在XML中绘制的图标。

谢谢。我使用我自己的主题,但是父级是theme.MaterialComponents.Light.NoActionBar。但是这还不够,我需要使用您所说的。谢谢。我使用我自己的主题,但父级是theme.MaterialComponents.Light.NoActionBar。但是这还不够,我需要使用您所说的。