java – Change Android Drawable Button Icon Programmatically-ThrowExceptions

Exception or error:

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

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

It has an initial android:src set as follows:

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

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

floatingActionButton.setImageResource(R.drawable.ic_media_pause);

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

Any help would be great appreciated. Thank you!

How to solve:

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

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

this will allow you to reference the default icons.

🙂

Leave a Reply

Your email address will not be published. Required fields are marked *