我們要將一張圖片顯示在螢幕上,首先需要建立一個顯示圖片的對象,在Android中,這個對象是ImageView對象,然後通過setImageResource
方法來設定要顯示的圖片資源索引。當然還可以對圖片執行一些其他的操作,比如設定它的Alpha值等。這裡將直接用一個樣本來分析ImageView的使
用,該樣本中通過一個線程來不斷更新Image的Alpha值。
MainActivity.java
package com.example.examples_04_15;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.app.Activity;import android.view.Menu;import android.widget.ImageView;import android.widget.TextView;public class MainActivity extends Activity {ImageView imageView;TextView textView;int image_alpha = 255;Handler mHandler = new Handler();boolean isrun = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);isrun = true;imageView = (ImageView)findViewById(R.id.ImageView01);textView = (TextView)findViewById(R.id.TextView01);imageView.setImageResource(R.drawable.log);imageView.setAlpha(image_alpha);//開啟一個線程來讓Alpha值遞減new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubwhile (isrun) {try {Thread.sleep(200);updateAlpha();} catch (InterruptedException e) {e.printStackTrace();}}}}).start();//接收訊息之後更新imageView視圖mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);imageView.setAlpha(image_alpha);textView.setText("現在alpha值是:" + Integer.toString(image_alpha));imageView.invalidate();}};}public void updateAlpha(){if (image_alpha - 7 >= 0) {image_alpha -= 7;}else{image_alpha = 0;isrun = false;}mHandler.sendMessage(mHandler.obtainMessage());}}
activity_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/TextView01" android:layout_below="@id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" /></RelativeLayout>