Setting the Image of an Image Button Control

As with an ImageView control, there are several different ways to set the graphic shown in an ImageButton control, including the following:

► setImageBitmap()—Use this method to set the graphic shown on the ImageButton control to a valid Bitmap object.

► setImageDrawable()—Use this method to set the graphic shown on the ImageButton control to a valid Drawable object.

► setImageResource()—Use this method to set the graphic shown on the ImageButton control to a valid Resource identifier.

► setImageURI()—Use this method to set the graphic shown on the ImageButton control to a valid Uri address.

In some circumstances, the ImageButton control will cache the graphic it is displaying, and continue to do so even if you use one of the methods to change the graphic. One workaround for this is to call setImageURI(null) to flush the previous graphic and then call setImageURI() again with a Uri set to the new graphic to display the ImageButton control.

'OSfr

Here's a handy trick for accessing application resources such as Drawable resources, using a specially constructed Uri address. This trick allows you to use the setImageURI() method of the ImageButton for both image resources and other graphics on the handset. Resource URIs can be referenced by resource identifier or by resource type/name. The Uri address format for the resource identifier method is as follows:

android.resource://[package]/[res id]

For example, you could use the following Uri to access a Drawable resource called avatar.png by its resource identifier: Uri path =

Uri.parse("android.resource://com.androidbook.triviaquiz13/" + R.drawable.avatar);

The Uri address format for the resource type/name method is as follows: android.resource://[package]/[res type]/[res name]

For example, you could use the following Uri to access a Drawable resource called avatar.png by its resource type/name:

Uri path = Uri.parse(

"android.resource://com.androidbook.triviaquiz13/drawable/avatar");

When you have a valid Uri for the Drawable resource, you can use it with the setImageURI() method of an ImageButton control as follows:

ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar); avatarButton.setImageURI(path);

0 0

Post a comment