ImageButton with text

Source: Internet
Author: User

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 ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.