映像狀態資源只能定義有限的幾種狀態。如果需要更多的狀態,就要使用映像層級資源。在該資源檔中可以定義任意多個映像層級。每個映像層級是一個整數區間,可以通過ImageView.setImageLevel或Drawable.setLevel方法切換不同狀態的映像。
映像層級資源是XML格式的檔案,必須將標籤作為XML的根節點。標籤中可以有任意多個標籤,每一個標籤表示一個層級區間。層級區間用android:minLevel和android:maxLevel屬性設定。setImageLevel或setLevel方法設定的層級在某個區間內(android:minLevel<=level<=android:maxLevel),系統就會先用哪個區間對應的映像(用android:drawable屬性設定)。在建立這個資源檔時,採用建立Android XML時,沒有根節點為的xml,不過這不要緊,可以建立一個全新的普通的XML檔案,然後寫入相應代碼即可。
下面我給出一個具體的執行個體(開關燈):
lamp.xml映像層級資源檔如下:
上面的lamp.xml檔案總共定義了兩個層級的映像資源。
下面給出首頁面布局檔案main_layout.xml檔案,如下:
相應的MainActivity的代碼如下:
package com.gc.drawablestudy;import android.os.Bundle;import android.annotation.SuppressLint;import android.app.Activity;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.Drawable;import android.view.Menu;import android.view.View;import android.widget.ImageView;import android.widget.TextView;/**author:Android將軍*/public class MainActivity extends Activity {private ImageView ivLamp;@SuppressLint(NewApi)@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Resources res=getResources();//Drawable drawable=res.getDrawable(R.drawable.bitmap_test);//TextView txt=(TextView)findViewById(R.id.textView);//txt.setBackground(drawable);ivLamp=(ImageView)findViewById(R.id.imageview_lamp);//設定level為8,顯示lamp_off.pngivLamp.setImageLevel(8);}//開燈按鈕的單擊事件方法public void onClick_LampOn(View view){//設定level為15,顯示lamp_on.pngivLamp.setImageLevel(15);}//關燈按鈕的單擊事件方法public void onClick_LampOff(View view){//設定level為6,顯示lamp_off.pngivLamp.setImageLevel(6);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
結合上一篇的博文,大家可以看出,映像狀態資源與映像層級資源都可以用來實現按鈕不同狀態顯示不同的映像的效果,如果你的控制只需顯示2個或3個效果你可以使用映像狀態資源,但是如果你想顯示更多的效果,還是使用映像層級資源。
案例效果如下:
轉載請註明出處:
http://blog.csdn.net/android_jiangjun/article/details/32308551