Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

ApiDemos 解析:ImageView 與 ImageButton 的尺寸、縮放與狀態切換

編輯:Android 開發實例

ImageView 與 ImageButton 是兩個最常被用到、也最常被誤用的圖像元件。本文以 ApiDemos 的範例為骨架,把尺寸限制、縮放模式、自訂屬性擴充與 XML 狀態切換一次講完。

一、ImageView:先把尺寸行為搞對

範例版面檔位於 ApiDemos/res/layout/image_view_1.xml。它的結構是一個 ScrollView 包住 LinearLayout,內部用大圖与小圖各示範四種尺寸策略。ScrollView 有個硬性限制值得先記住:它只允許一個直接子節點,放兩個以上會直接編譯/執行失敗,所以要用 LinearLayout 或多層結構包住。

<ImageView
    android:src="@drawable/sample_1"
    android:adjustViewBounds="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:src="@drawable/sample_1"
    android:adjustViewBounds="true"
    android:maxWidth="50dip"
    android:maxHeight="50dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:src="@drawable/sample_1"
    android:background="#66FFFFFF"
    android:adjustViewBounds="true"
    android:maxWidth="70dip"
    android:maxHeight="70dip"
    android:padding="10dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:src="@drawable/sample_1"
    android:background="#66FFFFFF"
    android:scaleType="centerInside"
    android:padding="10dip"
    android:layout_width="70dip"
    android:layout_height="70dip" />

四段差異對照下來,幾個屬性的分工就很清楚:

  • android:adjustViewBounds:設為 true 時,ImageView 會依圖片實際比例調整自身邊界,避免圖被硬撐變形。
  • android:maxWidth/android:maxHeight:限制圖像顯示的最大寬度與最大高度(注意 maxWidth 是寬度,不是高度)。這兩個上限只有搭配 adjustViewBounds 或 wrap_content 才有意義,因為一旦寬高寫死成固定值,上限就不再是決定因素。
  • android:padding:在圖像四周留出內距,會實際壓縮可用於繪圖的區域;android:paddingTop 則只設定上側間距,範例用它把每個 TextView 與上一組拉開 10dip。
  • android:background:墊在圖像底下的底色,範例用半透明白 #66FFFFFF 讓 padding 區域看得出來。
  • android:scaleType:決定圖像如何在自身邊界內縮放與對齊,是這幾個屬性裡最關鍵的一個。

scaleType 的可用值如下:

值說明
matrix不縮放,以左上角為基準做位移裁切
fitXY不保持比例,直接拉满整個邊界(會變形)
fitStart保持比例縮放至可容納,靠左上對齊
fitCenter保持比例縮放至可容納,置中對齊(最常用)
fitEnd保持比例縮放至可容納,靠右下對齊
center不縮放,置中顯示,超出部分被裁切
centerCrop保持比例放大到填满邊界,溢出部分裁切
centerInside保持比例縮小至可容納,置中;比圖小的情況則不放大

對應的 Java 程式碼非常單純,只是把版面載入:

public class ImageView1 extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_view_1);
    }
}

二、把 ImageView 與 TextView 包成一個擴充元件

範例裡每張圖都跟著一個說明文字,從維護角度看相當累贅。改善方式是自己做一個元件,把「圖 + 文」與排版方向一起封裝。

步驟是:建立 com.terry.Ext 套件,新增 imageViewExt 類別並繼承 LinearLayout,在建構子中從 AttributeSet 讀取自訂屬性,最後依屬性載入不同的版面檔。

package com.terry.Ext;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class imageViewExt extends LinearLayout {

    private TextView tv;
    private String labelText;
    private int FontSize;
    private String Position;
    private Drawable bitmap;
    private ImageView iv;

    public imageViewExt(Context context, AttributeSet attrs) {
        super(context, attrs);

        int resourceid;
        resourceid = attrs.getAttributeResourceValue(null, "labelText", 0);
        if (resourceid == 0) {
            labelText = attrs.getAttributeValue(null, "labelText");
        } else {
            labelText = getResources().getString(resourceid);
        }
        if (labelText == null) {
            labelText = "預設";
        }

        resourceid = attrs.getAttributeResourceValue(null, "imgSrc", 0);
        if (resourceid > 0) {
            bitmap = getResources().getDrawable(resourceid);
        } else {
            throw new RuntimeException("圖像資源為空");
        }

        resourceid = attrs.getAttributeResourceValue(null, "FontSize", 0);
        if (resourceid == 0) {
            FontSize = attrs.getAttributeIntValue(null, "FontSize", 12);
        } else {
            FontSize = getResources().getInteger(resourceid);
        }

        resourceid = attrs.getAttributeResourceValue(null, "Position", 0);
        if (resourceid == 0) {
            Position = attrs.getAttributeValue(null, "Position");
        } else {
            Position = getResources().getString(resourceid);
        }
        if (Position == null) {
            Position = "left";
        }

        String infService = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li = (LayoutInflater) context.getSystemService(infService);
        if ("left".equals(Position)) {
            li.inflate(com.terry.R.layout.image_horizontal, this);
        } else if ("top".equals(Position)) {
            li.inflate(com.terry.R.layout.image_vertical, this);
        } else {
            throw new RuntimeException("必須為 top 和 left 屬性");
        }

        tv = (TextView) findViewById(com.terry.R.id.TextView01);
        iv = (ImageView) findViewById(com.terry.R.id.imageview1);
        iv.setImageDrawable(bitmap);
        tv.setTextSize((float) FontSize);
        tv.setText(labelText);
    }
}

這段程式碼的取捨思路是:每個屬性都先假設傳進來的是資源 ID,若取不到再退回讀字面值,最後補上預設值。這樣一來,屬性既能寫 @string/xxx 也能直接写字串,彈性最大。

兩個版面檔只差在 orientation:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
    <ImageView android:layout_width="wrap_content" android:id="@+id/imageview1"
        android:layout_height="wrap_content"></ImageView>
</LinearLayout>

另一支 image_vertical.xml 內容相同,只是 LinearLayout 加上 android:orientation="vertical"。

使用時寫成完整類別名稱即可,記住「套件名稱 + 類別名稱」這個規則:

<com.terry.Ext.imageViewExt android:id="@+id/img"
    android:clickable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    labelText="封裝 ImageExt"
    imgSrc="@drawable/stat_happy"
    Position="top" />

這裡有個實務上必須補的一環:labelText、imgSrc、FontSize、Position 這幾個自訂屬性要能在 XML 中通過編譯,必須先在 res/values/attrs.xml 裡以 declare-styleable 宣告,例如:

<declare-styleable name="imageViewExt">
    <attr name="labelText" format="string" />
    <attr name="imgSrc" format="reference" />
    <attr name="FontSize" format="integer" />
    <attr name="Position" format="string" />
</declare-styleable>

有了宣告,IDE 才有辦法對這些屬性提供提示與檢查。而 Position 的切換,就是這個元件最實用的地方——同一份程式碼能讓圖文並排或上下排列。

三、ImageButton:基本用法與狀態切換

ImageButton 的版面檔(ApiDemos/res/layout/image_button_1.xml)示範了三種常見寫法:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ImageButton
        android:layout_width="100dip"
        android:layout_height="50dip"
        android:src="@android:drawable/sym_action_call" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/sym_action_chat" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/sym_action_email" />
</LinearLayout>

android:src 指向 @android:drawable/ 開頭的資源時,用的是系統內建圖示,不必自己準備素材,適合快速做原型。對應的 Java 程式碼同樣只是載入版面:

public class ImageButton1 extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_button_1);
    }
}

四、只用 XML 做出按下/聚焦的視覺回饋

ImageButton 是 Button 的變型,點擊與觸控事件行為一致。要讓它在不同狀態下換圖,最乾淨的方式不是寫 Java,而是用 selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/button_pressed" />
    <item android:state_focused="true"
        android:drawable="@drawable/button_focused" />
    <!-- <item android:drawable="@drawable/icon" /> 預設狀態 -->
</selector>

然後把這張 selector 當成圖片來源指定給元件:

<ImageButton android:id="@+id/ImageButton01"
    android:src="@drawable/my_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

關鍵細節:這支 selector XML 必須放在 res/drawable 底下,系統才會把它當成可當圖片使用的資源來索引。清單中的順序有優先權意義,愈前面(愈特定的狀態)優先,最後一項不帶 state 的就是預設值。

五、一個常見的誤解:ImageButton 沒有文字

ImageButton 並不是 TextView 的子公司,因此沒有 android:text,也不支援 setText()。如果你需要「圖 + 文」的按鈕,有兩條路:一是改用 Button,把圖片設成 android:background 或 android:drawableTop 並搭配 android:text;二是像本文第二節那樣做複合元件,在自訂 View 中同時配置 ImageView 與 TextView。硬要替 ImageButton 加文字,最終都會走到這兩條路之一。

原文出處:
https://www.cnblogs.com/TerryBlog/archive/2010/08/01/1789915.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved