Java 以编程方式更改 Android 可绘制按钮图标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35121147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:20:08  来源:igfitidea点击:

Change Android Drawable Button Icon Programmatically

javaandroiddrawable

提问by Alexander Staroselsky

How would one change the android:srcXML property programatically of a FloatingActionButton or Button widget? I have a button defined as following within an activity:

如何以android:src编程方式更改FloatingActionButton 或 Button 小部件的XML 属性?我在活动中定义了一个按钮:

FloatingActionButton floatingActionButton = (FloatingActionButton) this.findViewById(R.id.start_button);

It has an initial android:srcset as follows:

它有一个初始android:src集合如下:

android:src="@android:drawable/ic_media_play"

I'm trying to utilize the setImageResource(int id)to change the android:srcXML property, but how to I access a Drawable icon such as ic_media_pauseafter a button click that occurs for example. When I try to pass in R.drawable.ic_media_pauseto the setImageResource()method I received an cannot resolve symbol error.

我正在尝试利用setImageResource(int id)来更改android:srcXML 属性,但是如何访问 Drawable 图标,例如ic_media_pause在发生单击按钮之后。当我尝试传入R.drawable.ic_media_pausesetImageResource()方法时,我收到了无法解析符号错误。

floatingActionButton.setImageResource(R.drawable.ic_media_pause);

floatingActionButton.setImageResource(R.drawable.ic_media_pause);

How do I get at the available R.drawableresources to pass it in as an argument.

我如何获取可用的R.drawable资源以将其作为参数传递。

Any help would be great appreciated. Thank you!

任何帮助将不胜感激。谢谢!

采纳答案by Andrew Senner

You're trying to access a default icon included in the SDK. You need to prefix your resource identifier with "android." For example:

您正在尝试访问 SDK 中包含的默认图标。您需要在资源标识符前加上“android”。例如:

floatingActionButton.setImageResource(android.R.drawable.ic_media_pause); 

this will allow you to reference the default icons.

这将允许您引用默认图标。

:)

:)