Androiddrawable the non-known efficient usage (reprint)

Source: Internet
Author: User

Androiddrawable those unknown and efficient usage
Reprint please indicate the source: http://blog.csdn.net/lmj623565791/article/details/43752383, this article from: "Zhang Hongyang Blog" 1, overview

Drawable in our usual development, the basic will be used, but also to everyone very useful. So what is drawable? A thing that can be drawn on canvas, and compared to view, does not need to consider measure, layout, just to consider how to draw (Canavs). Of course, for the drawable of traditional usage, we certainly are not unfamiliar, today mainly to bring you the following several drawable usage:

1, custom drawable, compared to the view, drawable is lightweight and easy to use. You can change the idea of view first and try the next drawable first when customizing to achieve an effect later.

2, the custom state, I believe that everyone is not unfamiliar with drawable, but have you ever tried to customize a state in the past?

3, using drawable to enhance our UI perfermance, how to use drawable to improve the performance of our UI.


2, drawable basic concept

In general, in addition to directly using the picture placed under the drawable, in fact, the use of drawable is related to XML, we can use shape, layer-list and other tags to draw some background, but also through the selector tag to define the state of the view of the effect, etc. Of course, the basic each tag corresponds to a real entity class, the relationship is as follows: (Image from: Cyril mottier:master_android_drawables)


Common usage here is not an example, the following begins to look at the focus of this article.

2. Custom drawable

About Custom drawable, you can write a class and then inherit from Drawable, like a custom view, of course, there is only one core method of customizing drawable, which is draw. So what does the custom drawable actually do? What can I do?

I believe you are not unfamiliar with rounded corners, circular pictures, and I have written through the custom view implementation of the way, specifically to refer to:

Android Bitmapshader Real-round, rounded pictures

Android Xfermode Real-round, rounded pictures

So I'm going to tell you today that without a custom view, custom drawable can be implemented, and it's simpler, more efficient, and more versatile (you can be a background for any view).

1, roundimagedrawable

The code is relatively simple, see below roundimagedrawable

Package Com.zhy.view;import Android.graphics.bitmap;import Android.graphics.bitmapshader;import Android.graphics.canvas;import Android.graphics.colorfilter;import Android.graphics.paint;import Android.graphics.pixelformat;import Android.graphics.rectf;import Android.graphics.shader.tilemode;import Android.graphics.drawable.drawable;public class Roundimagedrawable extends Drawable{private Paint mPaint;private Bitmap mbitmap;private RECTF rectf;public roundimagedrawable (Bitmap Bitmap) {mbitmap = Bitmap; Bitmapshader Bitmapshader = new Bitmapshader (bitmap, tilemode.clamp,tilemode.clamp); mpaint = new Paint (); Mpaint.setantialias (True); Mpaint.setshader (Bitmapshader);}  @Overridepublic void SetBounds (int left, int top, int. right, int. bottom) {super.setbounds (left, top, right, bottom); RECTF = New RECTF (left, top, right, bottom);} @Overridepublic void Draw (canvas canvas) {Canvas.drawroundrect (RECTF, +, mpaint);} @Overridepublic int Getintrinsicwidth () {return mbitmap.getwidth ();} @Overridepublic int Getintrinsicheight () {return mbitmap.getheight ();} @Overridepublic void Setalpha (int alpha) {Mpaint.setalpha (alpha);} @Overridepublic void Setcolorfilter (Colorfilter CF) {mpaint.setcolorfilter (cf);} @Overridepublic int getopacity () {return pixelformat.translucent;}}

The core code is draw, but we only need a line of ~~~~setalpha, Setcolorfilter, getopacity, draw these methods must be implemented, but in addition to draw thought, the others are very simple. Getintrinsicwidth, getintrinsicheight mainly for the view when using the wrap_content, provide a size, the default is 1 is not what we want. SetBounds is to set the scope of the drawing.

OK, the fillet picture is so realized, easy not ~ ~

Look at the usage:

Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.MV); ImageView IV = (ImageView) Findviewbyid ( R.id.id_one); iv.setimagedrawable (new Roundimagedrawable (bitmap));

OK, stick to our, two ImageView and a textview.


Can see, not only for ImageView to achieve fillet picture, and can as any view background, in ImageView in the case of stretching, with ScaleType can be. In other view as the background, if there is tension, please refer to: Android Bitmapshader real-time implementation of the round, rounded picture. Enough detail.

2, Circleimagedrawable

So, let's take a look at the custom circular drawable notation:

Package Com.zhy.view;import Android.graphics.bitmap;import Android.graphics.bitmapshader;import Android.graphics.canvas;import Android.graphics.colorfilter;import Android.graphics.paint;import Android.graphics.pixelformat;import Android.graphics.rectf;import Android.graphics.shader.tilemode;import Android.graphics.drawable.drawable;public class Circleimagedrawable extends drawable{private Paint mPaint;private int Mwidth;private Bitmap Mbitmap; Public circleimagedrawable (Bitmap Bitmap) {mbitmap = Bitmap; Bitmapshader Bitmapshader = new Bitmapshader (bitmap, tilemode.clamp,tilemode.clamp); mpaint = new Paint (); Mpaint.setantialias (True); Mpaint.setshader (bitmapshader); mwidth = Math.min (Mbitmap.getwidth (), MBitmap.getHeight ( ));} @Overridepublic void Draw (canvas canvas) {canvas.drawcircle (MWIDTH/2, MWIDTH/2, MWIDTH/2, mpaint);} @Overridepublic int Getintrinsicwidth () {return mwidth;} @Overridepublic int Getintrinsicheight () {return mwidth;} @Overridepublic void Setalpha (int alpha) {Mpaint.setalPHA (Alpha);} @Overridepublic void Setcolorfilter (Colorfilter CF) {mpaint.setcolorfilter (cf);} @Overridepublic int getopacity () {return pixelformat.translucent;}}

As surprisingly simple, take another look:


OK, the example of custom drawable over~~~ next look at the custom state.

The above reference: Romain guy ' s Blog

3. Custom drawable State

About drawable state,state_pressed God horse, I believe everyone has mastered the special proficiency.

So next, we have a requirement, similar to a mailbox, the message is shown in a ListView, but we need a state to identify the unread and read: So, we customize a state state_message_readed.


As you can see, if the message is read, our icon is open and has a light red background. So how do you do it with a custom drawable state?

The custom drawable state needs to be divided into the following steps:

1. res/values/Create a new XML file: Drawable_status.xml

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Messagestatus" >        <attr name= "state_message_readed" format= "boolean"/>    </declare-styleable></resources>


2, inherit the container of item

We have here the item Select Relativelayout implementation, we need to inherit it, and then make a copy of its Oncreatedrawablestate method, add our custom state at the appropriate time.

Package Com.zhy.view;import Com.zhy.sample.drawable.r;import Android.content.context;import Android.util.attributeset;import Android.widget.relativelayout;public class Messagelistitem extends RelativeLayout{ private static final int[] state_message_readed = {r.attr.state_message_readed};p rivate Boolean mmessgereaded = False;pu Blic Messagelistitem (Context context, AttributeSet Attrs) {Super (context, attrs);} public void setmessagereaded (Boolean readed) {if (this.mmessgereaded! = readed) {mmessgereaded = readed; Refreshdrawablestate ();}} @Overrideprotected int[] oncreatedrawablestate (int extraspace) {if (mmessgereaded) {final int[] drawablestate = Super.oncreatedrawablestate (Extraspace + 1); Mergedrawablestates (Drawablestate, state_message_readed); return Drawablestate;} Return Super.oncreatedrawablestate (Extraspace);}}

The code is not complex, declares a state_message_readed, and then, in the case of Mmessgereaded=true, joins our custom state through the Oncreatedrawablestate method.

Similar code, you can see Compoundbutton (checkbox Parent) of the source code, it has a checked state:

@Override    protected int[] oncreatedrawablestate (int extraspace) {        final int[] Drawablestate = Super.oncreatedrawablestate (Extraspace + 1);        if (isChecked ()) {            mergedrawablestates (drawablestate, Checked_state_set);        }        return drawablestate;    }

3. Use

Layout file:

< Com.zhy.view.MessageListItem xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" 50DP "android:background=" @ DRAWABLE/MESSAGE_ITEM_BG "> <imageview android:id=" @+id/id_msg_item_icon "android:layout_width=" 30d P "android:src=" @drawable/message_item_icon_bg "android:layout_height=" Wrap_content "Android:duplicat    Eparentstate= "true" android:layout_alignparentleft= "true" android:layout_centervertical= "true"/> <textview android:id= "@+id/id_msg_item_text" android:layout_width= "Match_parent" Android:layout_h eight= "Wrap_content" android:layout_centervertical= "true" android:layout_torightof= "@id/id_msg_item_icon"/& Gt;</com.zhy.view.messagelistitem> 

Very simple, an icon, a text;

Activity

Package Com.zhy.sample.drawable;import Com.zhy.view.messagelistitem;import Android.app.listactivity;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup; Import Android.widget.arrayadapter;import Android.widget.textview;public class Customstateactivity extends Listactivity{private message[] messages = new message[] {new message ("Gas bill overdue", true), new message ("Congratulatio NS, you ' ve won! ", true), new message (" I Love you! ", false), new message (" reply! ", false), new message (" You ignoring me ? ", false), new message (" Not heard from ", false), new message (" Electricity Bill ", true), new message (" Gas bill ", true), n EW message ("Holiday plans", false), new message ("Marketing stuff", false),}; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Getlistview (). Setadapter (New arrayadapter<message> (This,-1, messages) {private Layoutinflater Minflater = Layoutinflater.from (getcontext()); @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {if (Convertview = = null) {Convertview = Minflater.inflate (R.layout.item_msg_list,parent, false);} Messagelistitem Messagelistitem = (messagelistitem) Convertview; TextView TV = (TextView) Convertview.findviewbyid (R.id.id_msg_item_text); Tv.settext (GetItem (position). message); Messagelistitem.setmessagereaded (GetItem (position) readed); return convertview;}});}

The code is very simple, but you can see that we need to use the call setmessagereaded method inside the GetView, of course, some other states, must also be manually triggered, such as triggering pressed in Action_down. Do not tangle I do not use viewholder or anything, add it on the line.

This example refers to: Example from GitHub

4. Improve our UI Perfermance

Now people pay more and more attention to performance issues, in fact, there is no need to care about, but since everyone cares, here through Cyril Mottier:master_android_drawables ppt in an example to illustrate the use of drawable to improve the performance of our UI.

Let's look at this one:


Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @color/app_ Background "android:padding=" 8DP "> <imageview android:layout_width=" wrap_content "android:layou t_height= "wrap_content" android:layout_gravity= "center" android:layout_marginbottom= "24DP" ANDROID:SR c= "@drawable/logo"/> <linearlayout android:layout_width= "match_parent" android:layout_height= "48DP "android:layout_gravity=" bottom "android:orientation=" horizontal "> <button Android : layout_width= "0DP" android:layout_height= "Fill_parent" android:layout_weight= "1" Android : text= "@string/sign_up"/> <button android:layout_width= "0DP" android:layout_height= "fi Ll_parent "Android:layout_weight= "1" android:text= "@string/sign_in"/> </LinearLayout></FrameLayout> 

You can see that the outermost layer is framelayout just to set the background map and padding, so the layout is believed to have been written by many people.

And look at this layout as the app launches, the user's intuitive effect:


The user first sees a whiteboard and then displays our page. Next, we'll take advantage of drawable to improve our UI performance and user experience.

1, first, we remove our outermost framelayout, and then customize a drawable XML, called Logo.xml

<?xml version= "1.0" encoding= "Utf-8"? ><layer-list xmlns:android= "http://schemas.android.com/apk/res/ Android >    <item>        <shape android:shape= "Rectangle" >            <solid android:color= "@color/ App_background "/>        </shape>    </item>    <item android:bottom=" 48DP ">        <bitmap            android:gravity= "center"            android:src= "@drawable/logo"/>    </item></layer-list>

OK, this drawable is set up our background and logo;

2, as the windowbackground of our current activity

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <style        name= "Theme.Default.NoActionBar"        parent= "@android: Style/theme.holo.light.noactionbar" >        <item name= "Android:windowbackground" >@ Drawable/login</item>    </style></resources>

3, set to the activity:

<activityandroid:name= "loginactivity" android:theme= "@style/theme.default.noactionbar" >

Ok, this not only minimizes our layout, but now we have only one linearlayout and two buttons in the layout, and it improves the user experience, now the user's intuitive effect:


is not the experience much better, the individual likes this example ~ ~


OK, to this our article over the ~ ~ ~ most of the content reference from some of the cattle people write examples, examples or Bang bang, we read this article at the same time, you can dig some things ~ ~


SOURCE Click to download


---------------------------------------------------------------------------------

Group number: 423372824

Bo Master part of the video has been online, if you do not like boring text, please poke (first record, look forward to your support):

Video Directory Address: I recorded a video tutorial

Public number Please scan:

--------------------------------------------------------------------------------------------------------










Original link This article by Bean John Blog Backup expert remote One click release

Androiddrawable the non-known efficient usage (reprint)

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.