編輯:關於 Android 程式設計
ImageView(圖像視圖)直接繼承自 View,主要功能是顯示圖片。實際上它並不限於位圖——任何 Drawable 對象都可以交給它來渲染。ImageView 可以放入任意布局中,並且 Android 為它提供了縮放與著色等能力。
以下是幾個常用屬性,每個屬性都有對應的 getter 與 setter 方法:
scaleType 直接決定了圖片在控件內部的呈現方式,共有八種可選:
先準備一張 green.png 放到 drawable 目錄下(關於 Android 資源體系,後續再詳細說明)。布局代碼如下:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="scaleType:center,未縮放,位於 ImageView 中心" />
<ImageView
android:id="@+id/imageview1"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="#F00"
android:scaleType="center"
android:src="@drawable/green" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="scaleType:fitCenter,按比例縮放" />
<ImageView
android:id="@+id/imageview2"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="#FFF"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/green" />
</LinearLayout>
再顯式指定一下圖片尺寸:
android:layout_width="300dp" android:layout_height="200dp"
效果展示:

由於 ImageView 繼承自 View,代碼中可以直接用 setLayoutParams 改變尺寸,這個方法對 View 的所有子類都適用:
imageView.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));
如果父容器是 RelativeLayout,則要相應地換成:
imageView.setLayoutParams(new RelativeLayout.LayoutParams(newWidth, newHeight));
而旋轉則需要借助 Matrix 類。它表示一個 3×3 的坐標變換矩陣,可以在其上做平移、縮放、旋轉等操作,使用前必須顯式初始化。
下面這個示例提供了兩個 SeekBar:一個控制圖片大小,一個控制旋轉角度。圖片放大的上限通過 DisplayMetrics 取屏幕寬度減去最小寬度得到,避免超出屏幕。
布局代碼:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageview3"
android:layout_width="200dp"
android:layout_height="150dp"
android:scaleType="fitCenter"
android:src="@drawable/green" />
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="圖像寬度:240 圖像高度:150" />
<SeekBar
android:id="@+id/sbSize"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:max="240"
android:progress="120" />
<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="0°" />
<SeekBar
android:id="@+id/sbRotate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:max="360" />
</LinearLayout>
實現代碼:
package com.bgxt.imageviewdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
@SuppressLint("NewApi")
public class ChangeImageActivity extends Activity implements OnSeekBarChangeListener {
private int minWidth = 80;
private ImageView imageView;
private TextView textview1, textview2;
private Matrix matrix = new Matrix();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_changeimage);
imageView = (ImageView) findViewById(R.id.imageview3);
SeekBar seekbar1 = (SeekBar) findViewById(R.id.sbSize);
SeekBar seekbar2 = (SeekBar) findViewById(R.id.sbRotate);
textview1 = (TextView) findViewById(R.id.tv1);
textview2 = (TextView) findViewById(R.id.tv2);
// 以屏幕寬度作為圖片放大的上限,避免超出屏幕
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
seekbar1.setMax(dm.widthPixels - minWidth);
seekbar1.setOnSeekBarChangeListener(this);
seekbar2.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar.getId() == R.id.sbSize) {
int newWidth = progress + minWidth;
int newHeight = (int) (newWidth * 3 / 4);
imageView.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));
textview1.setText("圖像寬度:" + newWidth + " 圖像高度:" + newHeight);
} else if (seekBar.getId() == R.id.sbRotate) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.green);
// 以 (30, 60) 為旋轉中心設定角度
matrix.setRotate(progress, 30, 60);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
imageView.setImageBitmap(bitmap);
textview2.setText(progress + "°");
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
}
效果展示:



移動平台上不可能把所有資源都打包在本地,很多實時性內容需要聯網獲取。這裡通過一個「從網絡下載圖片並顯示到 ImageView」的例子來說明實現方式。
Android 4.0 之後新增了一項限制:不能在主線程中訪問網絡,必須另開子線程。但這又帶來新問題——子線程中無法直接操作 UI 控件。如果你使用的平台版本低於 4.0,就不存在這個困擾,直接在主線程中聯網並更新 UI 即可。
我的解決方案是:用 Thread 開子線程訪問網絡,再用 Handler 完成消息傳遞,把結果送回主線程更新界面。
Handler 主要承擔兩個職責:
發送時機很好把握,關鍵是主線程怎麼知道消息到了?Android 通過回調機制解決:開發者只需重寫 Handler 的 handleMessage(Message) 方法,Message 對象中封裝了發送過來的數據。
Handler 中幾個常用的消息方法:
Message 封裝了線程間傳遞的數據。對於簡單數據,可以直接用它的 arg1、arg2、what 等字段;對於稍複雜的數據,可以通過 getData() 拿到一個 Bundle,再用它的各類 putXxx/getXxx 方法存取基本類型。
如果需要傳遞對象,Bundle 提供了兩個方法,但對象類型必須實現相應接口:
好消息是,不少 Android 自帶的類(比如 Bitmap)已經實現了 Parcelable,可以直接使用。
還有一種更直接的方式:Message 自帶的 obj 字段是 Object 類型,可以放任意對象。Message 的幾個常用字段:
下面的示例用隨機數決定採用哪種方式傳遞 Bitmap。網絡訪問部分只給出代碼,不作展開。
布局代碼:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnInternet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下載網絡圖片" />
<TextView
android:id="@+id/tbMsgType"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/ivInternet"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
實現代碼:
package com.bgxt.imageviewdemo;
import java.util.Random;
import com.bgxt.httputils.HttpUtils;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
public class InternetImageActivity extends Activity {
private Button btnInternet;
private ImageView ivInternet;
private TextView tvMsgType;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internetimage);
btnInternet = (Button) findViewById(R.id.btnInternet);
ivInternet = (ImageView) findViewById(R.id.ivInternet);
tvMsgType = (TextView) findViewById(R.id.tbMsgType);
// 主線程的 Handler,負責接收子線程發來的消息
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bitmap bmp;
// 通過消息碼判斷使用了哪種傳遞方式
if (msg.what == 0) {
bmp = (Bitmap) msg.obj;
tvMsgType.setText("使用 obj 傳遞數據");
} else {
Bundle ble = msg.getData();
bmp = (Bitmap) ble.get("bmp");
tvMsgType.setText("使用 Bundle 傳遞數據");
}
ivInternet.setImageBitmap(bmp);
}
};
btnInternet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvMsgType.setText("");
ivInternet.setImageBitmap(null);
new Thread() {
@Override
public void run() {
try {
InputStream inputStream = HttpUtils.getImageViewInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = new Message();
// 隨機選擇一種傳遞方式
if (new Random().nextInt(10) / 2 == 0) {
msg.what = 0;
msg.obj = bitmap;
} else {
Bundle bun = new Bundle();
bun.putParcelable("bmp", bitmap);
msg.what = 1;
msg.setData(bun);
}
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
}
}
網絡訪問工具類:
package com.bgxt.httputils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
private final static String URL_PATH =
"https://ww4.sinaimg.cn/bmiddle/9e58dccejw1e6xow22oc6j20c80gyaav.jpg";
public static InputStream getImageViewInputStream() throws IOException {
InputStream inputStream = null;
URL url = new URL(URL_PATH);
if (url != null) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
inputStream = conn.getInputStream();
}
}
return inputStream;
}
}
效果展示:



切記不要忘記在清單文件中申請 <uses-permission android:name="android.permission.INTERNET" />,否則會拋出網絡訪問異常。
最後看一個常見需求:啟動頁圖片的進場動畫。核心就是三步——獲取控件、加載動畫資源、設置動畫並監聽結束。
mSplashItem_iv = (ImageView) findViewById(R.id.splash_loading_item);
// 在 res/anim 目錄下添加 splash_loading.xml
Animation translate = AnimationUtils.loadAnimation(this, R.anim.splash_loading);
translate.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
// 動畫結束後跳轉到主界面並關閉當前頁
openActivity(HomeActivity.class);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
SplashActivity.this.finish();
}
});
mSplashItem_iv.setAnimation(translate);
動畫描述文件放在 res/anim 目錄下,例如一個簡單的平移動畫:
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate
android:duration="1500"
android:fromXDelta="0"
android:toXDelta="100%p" />
<alpha
android:duration="1500"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
</set>
這裡只是移動一段距離的簡單示例,動畫體系本身還有很多可玩的地方(插值器、延遲、循環次數、組合動畫等),值得另外專門深入。
Android 訊息提示 BadgeView:為檢視加上未讀紅點
在聊天、通知或購物應用中,常需要在某個檢視上顯示未讀數量或提示紅點。BadgeView 就是一種常見的實作方式,可將文字標籤疊加在任意 View 上。 基本概念 Bad
Android 開發實戰:接收系統廣播訊息
BroadcastReceiver 除了接收應用自己發送的廣播之外,還有一個更實用的用途:監聽系統廣播。如果應用需要在系統的特定時刻執行某些操作,透過監聽系統廣播來實現往
Android 計時器控件 Chronometer 用法詳解
Android 計時器控件 Chronometer 用法詳解 Chronometer 是 Android 內建的計時元件,適合做秒表或倒計時顯示。以下整理其常用方法與實作
Android 日曆控件:KCalendar 使用與自訂
日曆控件的效果在需要選擇日期的應用中,自訂日曆控件能提供更貼近品牌風格的體驗。KCalendar 這類控件通常支援月份切換、日期標記、點擊監聽與彈出視窗整合。以 Popu