Android Series Lectures (2): Add Borders to the textview component

Source: Internet
Author: User
This article is original. If you need to reprint it, please indicate the author and the source. Thank you!

Source code

AndroidProvided by the system itselfTextviewThe widget does not support borders, but you canTextviewTo add borders. We can use the following two methods:TextviewAdd a border for the widget.

1.Compile an inheritanceTextviewClass, andOndrawDraw borders in the event method.

2.Use9-patchFormat ImageTextviewTo set the border (this background image requires a border ).

InOndrawIt is very easy to draw borders in the event method.TextviewThe top, bottom, left, and right sides of the widget. TheCodeAs follows:

Package Net. blogjava. Mobile;

ImportAndroid. content. context;
ImportAndroid. Graphics. Canvas;
ImportAndroid. Graphics. paint;
ImportAndroid. util. attributeset;
ImportAndroid. widget. textview;

Public Class Bordertextview Extends Textview
{
@ Override
Protected Void Ondraw (canvas)
{
Super . Ondraw (canvas );
Paint paint = New Paint ();
// Set the border to black
Paint. setcolor (Android. Graphics. color. Black );
// Draw four sides of textview
Canvas. drawline ( 0 , 0 , This . Getwidth () - 1 , 0 , Paint );
Canvas. drawline ( 0 , 0 , 0 , This . Getheight () - 1 , Paint );
Canvas. drawline ( This . Getwidth () - 1 , 0 , This . Getwidth () - 1 , This . Getheight () - 1 , Paint );
Canvas. drawline ( 0 , This . Getheight () - 1 , This . Getwidth () - 1 , This . Getheight () - 1 , Paint );
}
Public Bordertextview (context, attributeset attrs)
{
Super (Context, attrs );
}
}

Note: If you want to textview transparent, that is, the textview the background color of the parent view is textview the background color of the component, 2 section 3 textview components that must be transparent with borders PNG image (except the border, the rest of the image is transparent ), then generate an image in 9-patch format.

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.