Because the SDK provides ImageButton can only add pictures, cannot add text, and the button control added text can only be displayed inside the picture, when we need to add text outside the picture can not meet our needs, gu can only write a custom ImageButton. Say is ImageButton, actually not inherit in ImageButton, but inherit from LinearLayout, because LinearLayout is linear arrangement, pass SetOrientation (linearlayout.vertical To achieve the purpose of view vertical arrangement, so it is simple to add two view: one ImageView and one textview. The code is as follows:
Packagecom.example.adtest;ImportAndroid.content.Context;ImportAndroid.widget.ImageView;Importandroid.widget.LinearLayout;ImportAndroid.widget.TextView; Public classImagebuttonexextendsLinearLayout {PrivateImageView _imageview =NULL; PrivateTextView _textview =NULL; PublicImagebuttonex (Context context) {Super(context); } PublicImagebuttonex (Context context,intImageresid,intTextresid) { Super(context); //TODO auto-generated Constructor stub_imageview=NewImageView (context); _textview=NewTextView (context); _imageview.setimageresource (IMAGERESID); _textview.settext (TEXTRESID); _imageview.setpadding (0, 0, 0, 0); _textview.setpadding (0, 0, 0, 0); Setclickable (true); Setfocusable (true); Setbackgroundresource (Android. R.drawable.btn_default); SetOrientation (linearlayout.vertical); AddView (_imageview); AddView (_textview); } Public voidSetbtntext (charsequence text) {_textview.settext (text); }}
Add a linearlayout as a container for Imagebuttonex.
<linearlayout android:id= "@+id/llimagebtnex" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:orientation= "vertical"/>
Then add the calling code to the activity:
Packagecom.example.adtest;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;Importandroid.widget.LinearLayout; Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); FinalImagebuttonex Imagebtnex =NewImagebuttonex ( This, R.drawable.icon, R.string.hello_world); Imagebtnex.setonclicklistener (NewButton.onclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubImagebtnex.setbtntext ("Already clicked"); }}); LinearLayout Llimagebtnex=(LinearLayout) Findviewbyid (R.id.llimagebtnex); Llimagebtnex.addview (Imagebtnex); } }