Android UI highlights-1. Android Drawable Classification summary (3/3), 1. androiddrawable

Source: Internet
Author: User

Android UI highlights-1. Android Drawable Classification summary (3/3), 1. androiddrawable

Android UI collection-1. Android Drawable Classification summary (3/3)

~ For more information, see coder-pig.


This section introduces:

We have learned about the Drawable of Android 2/3 in the previous two sections. In this section, we will

1/3 I learned it ~ They are:

LayerDrawable, TransitionDrawable, LevelListDrawable and StateListDrawable,

Now, start this section ~



Body of this section:

Outline diagrams of various Android Drawable types:



1. LayerDrawable:

It is actually a layer graphics object that contains a Drawable array, and then draws them according to the order corresponding to the array, Index

Drawable with the largest value will be drawn at the top! Although the Drawable has overlapping or overlapping areas

They are located at different layers, so they do not affect each other.<Layer-list.../>As the root node!


Related attributes:

Drawable: The referenced bitmap resource. If it is empty, Xu has a child node of the Drawable type.

Left: left margin of the layer relative to the container

Right: The right margin of the layer relative to the container

Top: The top margin of the layer relative to the container

Bottom: bottom margin of the layer relative to the container

Id: layer id


Sample Code:

Custom drag bar appearance (seekbar) and stacked image:

Let's take a look at it first:



, A custom progress bar and three stacked pictures!

The Code is also very simple. I will not explain the seekbar attributes ~

Layerlist_one.xml used by seekbar:

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:id="@android:id/background"        android:drawable="@drawable/seek_bkg"/>    <item        android:id="@android:id/progress"        android:drawable="@drawable/bar"/></layer-list>

Layerlist_two.xml of stacked images:

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item>        <bitmap android:src="@drawable/pig" android:gravity="center"/>    </item>    <item android:top="25dp" android:left="25dp">        <bitmap android:src="@drawable/pig" android:gravity="center"/>    </item>    <item android:top="50dp" android:left="50dp">        <bitmap android:src="@drawable/pig" android:gravity="center"/>    </item></layer-list>

Reference their main_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"    tools:context="com.jay.example.drawabletest.MainActivity" >    <SeekBar        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"        android:indeterminateOnly="false"        android:maxHeight="8dp"        android:minHeight="8dp"        android:progressDrawable="@drawable/layerlist_one"        android:thumb="@drawable/woniu"        android:thumbOffset="10dp" />    <ImageView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@drawable/layerlist_two"/>    </LinearLayout>


Okay, LayerDrawable is that simple ~






2. TransitionDrawable:

This Drawable is a subclass of the former LayerDrawable, But it manages two layers !!! Drawable, and provides

The animation with a change in transparency can control the animation effect of a Drawable layer over another Drawable layer, and the root node

Is<Transition.../>, remember that there are only two items! No more=-=, The property is similar to the former,

We need to call the startTransition method to start the switching animation between two layers. We can also play back the animation.

Animation: reverseTransition method!


A simple example:



The code is simple. Create a TransitionDrawable xml file:

<?xml version="1.0" encoding="utf-8"?><transition xmlns:android="http://schemas.android.com/apk/res/android" ><item android:drawable="@drawable/meinv1"/><item android:drawable="@drawable/meinv2"/></transition>

Next, set main_activity to get an ImageView, set src to point to the above drawable, and then in MainActivity:

Package com. jay. example. drawabletest; import android. app. activity; import android. graphics. drawable. animationDrawable; import android. graphics. drawable. transitionDrawable; import android. OS. bundle; import android. OS. handler; import android. widget. imageView; public class MainActivity extends Activity {private ImageView imgShow; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (save DInstanceState); setContentView (R. layout. activity_main); imgShow = (ImageView) findViewById (R. id. imgShow); TransitionDrawable td = (TransitionDrawable) imgShow. getDrawable (); td. startTransition (3000); // you can play it back and use reverseTransition ~ // Td. reverseTransition (3000 );}}

Okay, it's that simple. It's just one time, and the readers think it's boring. Pretty girls are not enough, right ~

Okay, here is a code written by someone else. I will post it to you here. If you are interested, you can study it. It is not complicated ~

Link: http://blog.csdn.net/lonelyroamer/article/details/8243606

The detailed code is as follows: (the core is to modify two images in Transition at hanler timing ~)

Package com. jay. example. drawabletest; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. graphics. drawable. bitmapDrawable; import android. graphics. drawable. drawable; import android. graphics. drawable. transitionDrawable; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. imageView; public class Mai NActivity extends Activity {private int change = 0; private ImageView imgShow; private Drawable [] drawables; private int [] ids = new int [] {R. drawable. meinv1, R. drawable. meinv2, R. drawable. meinv3, R. drawable. meinv4, R. drawable. meinv5}; // handle transition changes. private Handler handler = new Handler (new Handler. callback () {public boolean handleMessage (Message msg) {int duration = msg. arg1; TransitionDrawable t RansitionDrawable = null; transitionDrawable = new TransitionDrawable (new Drawable [] {drawables [change % ids. length], drawables [(change + 1) % ids. length]}); change ++; imgShow. setImageDrawable (transitionDrawable); transitionDrawable. startTransition (duration); return false ;}}); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity _ Main); imgShow = (ImageView) findViewById (R. id. imgShow); // load the images into Drawable ~ Based on the Resource id ~ BitmapFactory. options opts = new BitmapFactory. options (); opts. inJustDecodeBounds = true; BitmapFactory. decodeResource (getResources (), R. drawable. meinv1, opts); opts. inSampleSize = computeSampleSize (opts,-1,720*1280); opts. inJustDecodeBounds = false; drawables = new Drawable [ids. length]; try {for (int I = 0; I <ids. length; I ++) {// for Loop, load 5 drawable resources Bitmap bmp = BitmapFactory. decodeResource (getRes Ources (), ids [I], opts); drawables [I] = new BitmapDrawable (bmp) ;}} catch (Exception e) {e. printStackTrace ();} // enable the Thread and change transitionnew Thread (new MyRunnable ()). start () ;}// thread to send messages so that transition keeps changing private class MyRunnable implements Runnable {public void run () {while (true) {int duration = 3000; // change the interval Message message = handler. obtainMessage (); message. arg1 = duration; handler. sendMessage (message); try {T Hread. sleep (duration);} catch (InterruptedException e) {e. printStackTrace () ;}}}// calculate the appropriate image size public static int computeSampleSize (BitmapFactory. options options, int minSideLength, int maxNumOfPixels) {int initialSize = values (options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) {roundedSize = 1; while (roundedSize <initialSize) {roundedSize <= 1 ;}} else {rou NdedSize = (initialSize + 7)/8*8;} return roundedSize;} // calculate the appropriate image size. private static int computeInitialSampleSize (BitmapFactory. options options, int minSideLength, int maxNumOfPixels) {double w = options. outWidth; double h = options. outHeight; int lowerBound = (maxNumOfPixels =-1 )? 1: (int) Math. ceil (Math. sqrt (w * h/maxNumOfPixels); int upperBound = (minSideLength =-1 )? 128: (int) Math. min (Math. floor (w/minSideLength), Math. floor (h/minSideLength); if (upperBound <lowerBound) {// return the larger one when there is no overlapping zone. return lowerBound;} if (maxNumOfPixels =-1) & (minSideLength =-1) {return 1;} else if (minSideLength =-1) {return lowerBound;} else {return upperBound ;}}}

Run:





3. LevelListDrawable:

This is used to manage a set of Drawable. We can set different levels for the drawable,

When they draw, the corresponding drawable will be obtained based on the level Attribute Value to draw to the canvas, the root node

Is:<Level-list.../>He does not have any attribute nodes. That is to say, all we can do is set each <item>


Attributes that can be set for item:

Drawable: The referenced bitmap resource. If it is empty, Xu has a child node of the Drawable type.

Minlevel: Minimum value corresponding to level

Maxlevel: maximum value corresponding to level


Sample Code:

We dynamically modify the level value to achieve the following results:



Code implementation:

First, we compile a LevelListDrawable xml resource file:

<?xml version="1.0" encoding="utf-8"?><level-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item android:drawable="@drawable/cir1" android:maxLevel="2000"/>    <item android:drawable="@drawable/cir2" android:maxLevel="4000"/>    <item android:drawable="@drawable/cir3" android:maxLevel="6000"/>    <item android:drawable="@drawable/cir4" android:maxLevel="8000"/>    <item android:drawable="@drawable/cir5" android:maxLevel="10000"/></level-list>


Next we will go to MainActivity, a Timer, and handler to modify the level value ~

package com.jay.example.drawabletest;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.graphics.drawable.LevelListDrawable;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.ImageView;public class MainActivity extends Activity {private ImageView imgShow;private LevelListDrawable ld;private Handler handler = new Handler(){public void handleMessage(Message msg) {if(msg.what == 0x123){if(ld.getLevel() > 10000)ld.setLevel(0);else imgShow.setImageLevel(ld.getLevel()+2000);}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imgShow = (ImageView) findViewById(R.id.imgShow);ld = (LevelListDrawable) imgShow.getDrawable();imgShow.setImageLevel(0);new Timer().schedule(new TimerTask() {@Overridepublic void run() {handler.sendEmptyMessage(0x123);}}, 0,1000);}}



4. StateListDrawable:

It finally comes to the last Drawable. It seems unfamiliar. In fact, it is what we usually set a dynamic click background for the button.

Selector, haha. I can't get familiar with it anymore ~ For example, the buttons are in the following status: Press, select, click, and unavailable. In addition, a friend in the group today

Problem layout get thisSelecotrYes, of course. However, you must set a Clickable = "true" for the layout first!

You can set the following attributes:


Configurable attributes:

Drawable: The referenced Drawable bitmap. We can put it at the beginning to indicate the normal state of the component ~

State_focused: whether to obtain the focus

State_window_focused: whether to obtain the window focus

State_enabled: whether the control is available

State_checkable: whether the control can be checked. eg: checkbox

State_checked: whether the control is checked

State_selected: determines whether the control is selected.

State_pressed: whether the control is pressed

State_active: whether the control is in the active state, eg: slidingTab

State_single: determines whether only one sub-control is displayed when the control contains multiple sub-controls.

State_first: when the control contains multiple child controls, determine whether the first child control is displayed.

State_middle: when the control contains multiple child controls, determine whether a child control is displayed.

State_last: when the control contains multiple child controls, determine whether the last child control is displayed.



Code Demonstration:

Let's get the simplest selector. The buttons are pressed and not pressed. This is directly deducted from the project:

The content can be ignored directly, mainly because of the effect of clicking the logon button ~

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >    <item android:state_pressed="false" android:drawable="@drawable/ic_btn_select_add_course_normal"/><item android:state_pressed="true" android:drawable="@drawable/ic_btn_select_add_course_pressed"/></selector>

Next, set the background as follows:





The last two sentences are as follows:

Okay. Three articles in a row about Drawable in Android have come to an end without knowing it. Do readers get new moves?

For the next Part, we will learn some basics of graph processing, such as Bitmap, paint, canvas, and path ~

If you think this article is good, how can you give likes to more friends?








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.