"Android" Android implements custom button with text and pictures

Source: Internet
Author: User

  

In Android development, you will often need to use a button with text and pictures, below to explain the common implementation methods.

I. Using the system's own button implementation

The simplest way to do this is to use the button that comes with the system, which is the smallest amount of code. One of the properties of the button is Drawableleft, which can set the picture to the left of the text, but this way must make the background color of the icon transparent, if the background color of the icon is not transparent, it will cause the icon part of the background color will not be changed when the button is clicked.

Main code:

< Button      Android:id = "@+id/bt3"     android:layout_margintop= "4DP"    android:layout_width= "Wrap_content"      android:layout_height= "Wrap_content"    android:text= "Train"      android:textsize= "16sp"    android:textcolor= "#000000"      android:paddingleft= "5DP"    android:paddingtop= "5DP"      android:paddingright= "5DP"    android:paddingbottom= "5DP"      android:drawableleft= "@drawable/line_bus_icon"    Android:background  = "@drawable/button_bg">  </button>

Implementation results:

  

If you want to make the text below the icon, change to Drawabletop.

Two. Inherit the button of the system and redraw it

 Packagecom.test;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.util.AttributeSet;ImportAndroid.widget.Button; Public classImageTextButton2extendsButton {Private intResourceId = 0; PrivateBitmap Bitmap;  PublicImageTextButton2 (Context context) {Super(Context,NULL); }         PublicImageTextButton2 (Context context,attributeset attributeset) {Super(context, attributeset);  This. setclickable (true); ResourceId=R.drawable.icon; Bitmap=Bitmapfactory.decoderesource (Getresources (), resourceId); }         Public voidSetIcon (intresourceId) {         This. Bitmap =Bitmapfactory.decoderesource (Getresources (), resourceId);    Invalidate (); } @Overrideprotected voidOnDraw (canvas canvas) {//TODO auto-generated Method Stub//The top of the picture appears centered        intx = ( This. Getmeasuredwidth ()-bitmap.getwidth ())/2; inty = 0; Canvas.drawbitmap (bitmap, x, Y,NULL); //coordinates need to be converted because the text in the button is centered by default//you need to make the text appear at the bottom .Canvas.translate (0, ( This. Getmeasuredheight ()/2)-(int) This. GetTextSize ()); Super. OnDraw (canvas); }        }

Then call in the layout file:

< Com.test.ImageTextButton2    Android:id = "@+id/bt2"    android:layout_margintop= "10DP"   android:text= "Hello"    Android:textsize= "15DP"   android:textcolor= "#000000"    Android:layout_width= "60DP"   android:layout_height= "70DP"    Android:background = "@drawable/button_bg"  />

Note that when called in an XML file, it is not possible to use wrap_content for Layout_width and layout_height two properties, otherwise it will cause the button to display only the text part.

Three. Inherit the layout file

The analysis found that a button with text and icon can actually be viewed as a linear layout or a relative layout, so it can be implemented by inheriting the layout.

First implement a button's layout file Img_text_bt.xml:

<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content">    <ImageViewAndroid:id= "@+id/imgview"Android:layout_alignparenttop= "true"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true"android:src= "@drawable/icon">  </ImageView>    <TextViewAndroid:id= "@+id/textview"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true"Android:layout_below= "@id/imgview">  </TextView>  </Relativelayout>

Then go to inherit the Relativelayout layout:

 Packagecom.test;ImportAndroid.content.Context;ImportAndroid.util.AttributeSet;ImportAndroid.view.LayoutInflater;ImportAndroid.widget.ImageView;Importandroid.widget.RelativeLayout;ImportAndroid.widget.TextView; Public classImageTextButton1extendsRelativelayout {PrivateImageView Imgview; PrivateTextView TextView;  PublicImageTextButton1 (Context context) {Super(Context,NULL); }         PublicImageTextButton1 (Context context,attributeset attributeset) {Super(context, attributeset); Layoutinflater.from (context). Inflate (R.LAYOUT.IMG_TEXT_BT, This,true);  This. Imgview =(ImageView) Findviewbyid (R.id.imgview);  This. TextView =(TextView) Findviewbyid (R.id.textview);  This. setclickable (true);  This. setfocusable (true); }         Public voidSetimgresource (intResourceID) {         This. Imgview.setimageresource (ResourceID); }         Public voidSetText (String text) { This. Textview.settext (text); }         Public voidSetTextColor (intcolor) {         This. Textview.settextcolor (color); }         Public voidSettextsize (floatsize) {         This. textview.settextsize (size); }    }

You can then invoke it in the desired XML file:

< Com.test.ImageTextButton1     Android:id = "@+id/bt1"    android:layout_width= "Wrap_content"   android:layout_height= " Wrap_content "   android:background=" @drawable/button_bg "  />

Then use it in the activity:

BT1 = (ImageTextButton1) Findviewbyid (R.ID.BT1);        Bt1.settext ("icon");        Bt1.settextcolor (Color.rgb (0, 0, 0));        Bt1.setonclicklistener (new  Onclicklistener () {                        @Override            public  void  OnClick (View v) {                //  TODO auto-generated method stub                Toast.maketext (mainactivity.  this, "Bt1 was clicked", Toast.length_short). Show ();            }        );

Three different ways to run the final result:

Project Source: Http://files.cnblogs.com/dolphin0520/TestImgTextButton.rar

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.