There are many ways to implement ImageButton with text. Here I only list one method: Define a class inherited from ImageButton, and Override its onDraw (Canvas canvas) method.
? Public class MyImageButton extends ImageButton {
Private String text = null; // The text to be displayed
Private int color; // text color
Public MyImageButton (Context context, AttributeSet attrs ){
Super (context, attrs );
}
Public void setText (String text ){
This. text = text; // set text
}
Public void setColor (int color ){
This. color = color; // set the text color.
}
@ Override
Protected void onDraw (Canvas canvas ){
Super. onDraw (canvas );
Paint paint = new Paint ();
Paint. setTextAlign (Paint. Align. CENTER );
Paint. setColor (color );
Canvas. drawText (text, 15, 20, paint); // draw text
}
}
The following is a test. Two MyImageButton-type controls, button01 and button02, are defined in the layout file.
? <? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content">
<Com. alex. layout. MyImageButton
Android: id = "@ + id/button01"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: background = "@ drawable/button_bg"
/>
<Com. alex. layout. MyImageButton
Android: id = "@ + id/button02"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: background = "@ drawable/button_bg"
/>
</LinearLayout>
Finally, set the color of the text and text to be displayed in the activity respectively.
? Button01 = (MyImageButton) findViewById (R. id. button01 );
Button01.setText ("Haha ");
Button01.setColor (Color. RED );
Button02 = (MyImageButton) findViewById (R. id. button02 );
Button02.setColor (Color. BLUE );
Button02.setText ("Haha ");