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

Android ApiDemo 逐項拆解:Graphics 與 View 篇(下)

編輯:初階開發

接續上一篇,這裡整理 ApiDemo 中 Gallery、Grid、ImageSwitcher、ImageView、LayoutAnimation 與 LinearLayout 這幾組範例。這些範例的共通主題是「容器與版面配置」,也是最容易被忽略卻最影響成品質感的環節。

16. CustomView1 —— 自訂 View 與自屬性

這個範例示範如何寫一個自己的 View(com.example.android.apis.view.LabelView),並在 XML 裡直接指定自訂屬性 app:text、app:textSize、app:textColor。

關鍵是命名空間宣告:xmlns:app="https://schemas.android.com/apk/res/com.example.android.apis"。這串 URI 的格式固定為 https://schemas.android.com/apk/res/ 加上你的 package 名稱,Android 會據此找到 res/values/attrs.xml 裡以 <declare-styleable> 定義的屬性集合。

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

    <com.example.android.apis.view.LabelView
        android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Red"/>

    <com.example.android.apis.view.LabelView
        android:background="@drawable/blue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Blue" app:textSize="20dp"/>

    <com.example.android.apis.view.LabelView
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:text="Green" app:textColor="#ffffffff" />
</LinearLayout>

17. DateWidgets1 —— 日期時間控制項

展示 TimePicker 與 DatePicker 等日期時間元件的用法。

18 / 19. ExpandableList1 與 3 —— 可展開清單

兩者都基於 android.widget.ExpandableListAdapter,差別在於資料綁定的方式與自訂程度。

20. Focus1 —— WebView 的焦點問題

用 WebView.loadData() 塞入一段 HTML,示範 WebView 內的連結無法取得焦點的行為:

WebView webView = (WebView) findViewById(R.id.rssWebView);
webView
    .loadData(
            "<html><body>Can I focus?<br /><a href=\"#\">No I cannot!</a>.</body></html>",
            "text/Html", "utf-8");

這牽涉到 WebView 的焦點鏈與 Android 焦點搜尋機制的互動,在混用原生元件與 WebView 的畫面上特別容易遇到。

21. Gallery1 —— 長按選單

長按圖片會彈出 ContextMenu,選擇項目後以 Toast 顯示被按下的位置。

public class Gallery1 extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_1);

        // Reference the Gallery view
        Gallery g = (Gallery) findViewById(R.id.gallery);
        // Set the adapter to our custom adapter
        g.setAdapter(new ImageAdapter(this));

        // Set an item click listener, and just Toast the clicked position
        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });

        // 為長按項目註冊 ContextMenu
        registerForContextMenu(g);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        menu.add(R.string.gallery_2_text);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Toast.makeText(this, "Longpress: " + info.position, Toast.LENGTH_SHORT)
                .show();
        return true;
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            mContext = c;
            // 讀出自訂的 Gallery 項目背景
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
            i.setImageResource(mImageIds[position]);
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(136, 88));
            // 套用偏好的 Gallery 項目背景
            i.setBackgroundResource(mGalleryItemBackground);
            return i;
        }

        private Context mContext;

        private Integer[] mImageIds = {
            R.drawable.gallery_photo_1, R.drawable.gallery_photo_2,
            R.drawable.gallery_photo_3, R.drawable.gallery_photo_4,
            R.drawable.gallery_photo_5, R.drawable.gallery_photo_6,
            R.drawable.gallery_photo_7, R.drawable.gallery_photo_8 };
    }
}

幾個值得注意的細節:registerForContextMenu() 是啟用長按選單的必要步驟;onContextItemSelected 中要透過 AdapterContextMenuInfo.position 才能取得被長按的項目索引;obtainStyledAttributes 用完務必呼叫 recycle() 釋放資源。

22. Grid1 —— GridView 版面

<GridView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/myGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />

numColumns="auto_fit" 會依 columnWidth 自動算出能塞幾欄,stretchMode="columnWidth" 則把剩下的空間平均分給各欄。這兩個屬性搭配使用,才能做出自適應的網格。

23. Grid2 —— 重用 convertView

setContentView(R.layout.grid_2);

GridView g = (GridView) findViewById(R.id.myGrid);
g.setAdapter(new ImageAdapter(this));

這裡的 getView() 示範了 Adapter 最重要的效能技巧——複用 convertView:

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
        imageView.setAdjustViewBounds(false);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);

    return imageView;
}

只有在沒有可回收的 View 時才 new 一個新的,其餘情況直接重用並換掉圖片。少了這個判斷,長清單滾動時會不斷配置物件,直接導致卡頓。

24. ImageSwitcher1 —— 圖片切換器

ImageSwitcher 與 Gallery 搭配,Gallery 選中項目時,切換區顯示對應的大圖。

public class ImageSwitcher1 extends Activity implements
        AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_switcher_1);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);                      // 注意這行
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
    }

    // Gallery 被選後設置 ImageSwitcher 的圖片
    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        mSwitcher.setImageResource(mImageIds[position]);
    }

    public void onNothingSelected(AdapterView parent) {
    }

    // 建立要放進 ViewSwitcher 的新 View
    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        return i;
    }

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
            i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);                 // 保持長寬比
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }

        private Context mContext;
    }

    private Integer[] mThumbIds = {
            R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
            R.drawable.sample_thumb_2, R.drawable.sample_thumb_3,
            R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
            R.drawable.sample_thumb_6, R.drawable.sample_thumb_7 };

    private Integer[] mImageIds = {
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7 };
}

使用 ImageSwitcher 有兩個必要步驟:setFactory(this) 讓 Activity 成為 View 工廠,並實作 makeView() 回傳要顯示的 View。切換動畫則靠 setInAnimation / setOutAnimation。注意範例中同時準備了 mThumbIds(縮圖)與 mImageIds(原圖)兩組資源, respectively 給 Gallery 與 ImageSwitcher 使用。

25. ImageView1 —— 縮放與邊距的組合

這個範例用同一張大圖示範四種尺寸策略,是釐清 ImageView 屬性最容易混淆之處的最佳教材。

先看不設限制的基準:只有 android:adjustViewBounds="true",圖片以原始尺寸顯示、保持比例。

接著用 maxWidth / maxHeight 限制在 50×50 以內:

限制在 70×70 並加上 10dip padding:

最後一種是固定 70×70 並加 padding:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <!-- 以下四例使用大圖 -->

        <!-- 1. 不縮放,作為對照 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_large_normal"/>
        <ImageView
            android:src="@drawable/sample_1"
            android:adjustViewBounds="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <!-- 2. 最多縮到 50x50 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_large_at_most"/>
        <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" />

        <!-- 3. 最多 70x70,四周留 10dip 內距 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_large_at_most_padded"/>
        <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" />

        <!-- 4. 固定 70x70,四周留 10dip 內距 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_large_exactly_padded"/>
        <ImageView
            android:src="@drawable/sample_1"
            android:background="#66FFFFFF"
            android:scaleType="centerInside"
            android:padding="10dip"
            android:layout_width="70dip"
            android:layout_height="70dip" />

        <!-- 以下四例改用小圖重複示範 -->

        <!-- 1. 不縮放,作為對照 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_small_normal"/>
        <ImageView
            android:src="@drawable/stat_happy"
            android:background="#FFFFFFFF"
            android:adjustViewBounds="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <!-- 2. 最多縮到 50x50 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_small_at_most"/>
        <ImageView
            android:src="@drawable/stat_happy"
            android:background="#FFFFFFFF"
            android:adjustViewBounds="true"
            android:maxWidth="50dip"
            android:maxHeight="50dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <!-- 3. 最多 70x70,四周留 10dip 內距 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_small_at_most_padded"/>
        <ImageView
            android:src="@drawable/stat_happy"
            android:background="#FFFFFFFF"
            android:adjustViewBounds="true"
            android:maxWidth="70dip"
            android:maxHeight="70dip"
            android:padding="10dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <!-- 4. 固定 70x70,四周留 10dip 內距 -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="@string/image_view_small_exactly_padded"/>
        <ImageView
            android:src="@drawable/stat_happy"
            android:background="#FFFFFFFF"
            android:scaleType="centerInside"
            android:padding="10dip"
            android:layout_width="70dip"
            android:layout_height="70dip" />
    </LinearLayout>
</ScrollView>

這裡最該記住的三個觀念:

  • adjustViewBounds 讓 View 依圖片比例自動調整邊界,圖片才不會被拉變形。
  • maxWidth / maxHeight 是「上限」,圖片比上限小時不會被放大;layout_width / layout_height 是「固定值」,會強制該尺寸。這正是「at most」與「exactly」的差別。
  • scaleType="centerInside" 在固定尺寸的 View 裡讓圖片完整呈現並居中,是第四種寫法能正常顯示的原因。

26. LayoutAnimation2 —— ListActivity 的載入動畫

這個範例用 Alpha + Translate 組合,讓清單項目逐個淡入並從下方滑上。

public class LayoutAnimation2 extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));

        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(50);
        set.addAnimation(animation);

        animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        animation.setDuration(100);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(set,
                0.5f);
        ListView listView = getListView();
        listView.setLayoutAnimation(controller);
    }

    private String[] mStrings = {
            "Bordeaux", "Lyon", "Marseille", "Nancy",
            "Paris", "Toulouse", "Strasbourg" };
}

關鍵是 LayoutAnimationController 的第二個參數 0.5f——它是每個項目之間的延遲比例,數值越小,項目出現得越快。Animation.RELATIVE_TO_SELF 搭配 -1.0f 代表「自身高度的負一倍」,也就是從下方一個身位的位置滑入。

27. LayoutAnimation3 —— 用 XML 宣告版面動畫

同一件事也可以用純 XML 完成,在 ListView 上掛 android:layoutAnimation 即可:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

res/anim/layout_bottom_to_top_slide.xml 宣告版面動畫本身,並在 android:animation 指定實際要套用的動畫:

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="30%"
    android:animationOrder="reverse"
    android:animation="@anim/slide_right" />

實際動畫 slide_right.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_shortAnimTime" />
</set>

android:animationOrder="reverse" 讓動畫順序反過來跑;android:delay="30%" 是相對前一個項目的延遲比例。另外注意 duration 直接引用 @android:integer/config_shortAnimTime,這是系統定義的時間常數,跟隨系統設定變動,比寫死毫秒數更恰當。

28. LayoutAnimation4 —— 隨機順序淡入

GridView 掛上 android:layoutAnimation="@anim/layout_random_fade":

<GridView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_random_fade"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />

layout_random_fade.xml 的重點是 android:animationOrder="random",並搭配 android:delay="0.5":

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="0.5"
    android:animationOrder="random"
    android:animation="@anim/fade" />

fade.xml:

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="0.0" android:toAlpha="1.0"
    android:duration="@android:integer/config_longAnimTime" />

29. LayoutAnimation5 —— gridLayoutAnimation 與方向控制

這次改用 gridLayoutAnimation,它能控制動畫的傳播方向:

<GridView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_grid_inverse_fade"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />

layout_grid_inverse_fade.xml:

<?xml version="1.0" encoding="utf-8"?>
<gridLayoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:columnDelay="0.5"
    android:directionPriority="row"
    android:direction="right_to_left|bottom_to_top"
    android:animation="@anim/fade" />

android:direction 可用 | 組合多個方向:left_to_right、right_to_left、top_to_bottom、bottom_to_top。directionPriority 決定優先行別還是列別(row / column / none),columnDelay 與 rowDelay 則分別控制兩個軸向的延遲。fade.xml 與上一例相同。

30. LayoutAnimation6 —— 波紋放大縮小

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/grid"
    android:layoutAnimation="@anim/layout_wave_scale"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:verticalSpacing="10dp"

    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"

    android:gravity="center" />

layout_wave_scale.xml:

<?xml version="1.0" encoding="utf-8"?>
<gridLayoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:rowDelay="75%"
    android:columnDelay="0%"
    android:directionPriority="none"
    android:animation="@anim/wave_scale" />

這裡 rowDelay="75%" 而 columnDelay="0%"`,加上 directionPriority="none",效果是同一列同時啟動、往下一列遞延,看起來就像一道波紋掃過。

wave_scale.xml 用兩段 scale 串接,做出「放大再縮回」的彈跳感:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="100" />
    <scale
        android:fromXScale="0.5" android:toXScale="1.5"
        android:fromYScale="0.5" android:toYScale="1.5"
        android:pivotX="50%" android:pivotY="50%"
        android:duration="200" />
    <scale
        android:fromXScale="1.5" android:toXScale="1.0"
        android:fromYScale="1.5" android:toYScale="1.0"
        android:pivotX="50%" android:pivotY="50%"
        android:startOffset="200"
        android:duration="100" />
</set>

第二段 scale 用 android:startOffset="200" 接在 200ms 之後啟動,形成放大→回落的連續動作。

31. LayoutAnimation7 —— 每個 TableRow 各自的動畫

這個範例把版面動畫套在 TableLayout 的每一列上,每列左右交錯滑入。

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layoutAnimation="@anim/layout_animation_table"
    android:animationCache="false"
    android:clipToPadding="false"
    android:padding="12dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_right_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_name" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_left_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_lastname" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_right_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_phone" />
        <EditText />
    </TableRow>

    <TableRow
        android:layoutAnimation="@anim/layout_animation_row_left_slide">
        <TextView
            android:gravity="right"
            android:text="@string/layout_animation_address" />
        <EditText android:lines="3" />
    </TableRow>
</TableLayout>

最後那個 <EditText android:lines="3" /> 讓位址欄變成三行高。另外 android:animationCache="false" 是必要的——版面動畫搭配快取時常出現顯示異常,關掉比較保險。

左右滑入的動畫定義:

<!-- layout_animation_row_left_slide.xml -->
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="10%"
    android:animation="@anim/slide_left" />

<!-- slide_left.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="@android:integer/config_shortAnimTime" />
</set>

<!-- layout_animation_row_right_slide.xml -->
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="10%"
    android:animationOrder="reverse"
    android:animation="@anim/slide_right" />

<!-- slide_right.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_shortAnimTime" />
</set>

32. LinearLayout3 —— layout_weight 分配剩餘空間

三個 TextView 縱向堆疊,中間那個設 android:layout_weight="1",於是它吃掉了所有剩餘空間。

<?xml version="1.0" encoding="utf-8"?>
<!--
    Demonstrates a simple linear layout. The layout fills the screen, with the
    children stacked from the top. The middle child gets allocated any extra
    space.
-->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- view1 goes on top -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_3_top"/>

    <!-- view2 goes in the middle -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/linear_layout_3_middle"/>

    <!-- view3 goes on the bottom -->
    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_3_bottom"/>
</LinearLayout>

layout_weight 的運作方式:先配置給有固定尺寸的元件,剩下的空間再依 weight 比例分給其他元件。

33. LinearLayout4 —— 等寬欄位

水平排列四個色塊,每個都設 android:layout_width="0dip" 加 android:layout_weight="1",結果是四等分。

<?xml version="1.0" encoding="utf-8"?>
<!-- Demonstrates a horizontal linear layout with equally sized columns -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:background="@drawable/red"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/green"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/blue"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>

    <TextView
        android:background="@drawable/yellow"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>
</LinearLayout>

這裡有個實務上很重要的細節:使用 weight 分欄時,該方向的尺寸要寫 0dip 而不是 fill_parent。寫成 fill_parent 會先佔滿整個寬度再來分 weight,容易出現超出畫面的情況。0dip 是為了讓 weight 機制有乾淨的起點。

34. LinearLayout5 —— 巢狀版面做表單

示範用巢狀 LinearLayout 組出一個表單:說明文字、輸入框,再用一個水平 LinearLayout 裝兩個按鈕並靠右對齊。

<?xml version="1.0" encoding="utf-8"?>
<!-- Demonstrates a nesting layouts to make a form -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dip">

    <!-- TextView goes on top... -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_5_instructions"/>

    <!--
        Followed by the EditText field...

        Also give it a standard background (the "android:" part in
        @android:drawable/editbox_background means it is a system resource
        rather than an application resource).
    -->
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"/>

    <!--
        Use a horizontal layout to hold the two buttons. This item has
        layout_gravity="right". This means the whole horizontal LinearLayout
        is right aligned, not the individual items within it. The horizontal
        LinearLayout's width is set to wrap_content. (If it was fill_parent
        it would not have any room to slide to the right.)
    -->
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/linear_layout_5_cancel"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text="@string/linear_layout_5_ok" />
    </LinearLayout>
</LinearLayout>

原始碼的註解講得很清楚,值得特別記住兩點:@android:drawable/ 前綴代表系統資源,@drawable/ 代表應用程式自己的資源;而 android:layout_gravity="right" 只有在該容器的寬度是 wrap_content 時才有效果——若寫成 fill_parent,容器已經佔滿整行,就沒有空間可以往右滑了。

35. LinearLayout6 —— wrap_content 與 fill_parent 的組合

父容器用 wrap_content 加上 20dip padding,子元件用 fill_parent,結果是四個方塊寬度一致並整體被撐開。

<?xml version="1.0" encoding="utf-8"?>
<!--
    LinearLayout which uses a combination of wrap_content on itself and
    fill_parent on its children to get every item to be the same width.
-->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/blue"
    android:padding="20dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_6_one"/>

    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_6_two"/>

    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_6_three"/>

    <TextView
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_6_four"/>
</LinearLayout>

36. LinearLayout7 —— 高度不一致的等寬欄位

與 LinearLayout4 類似,但這次前兩欄用 fill_parent 撐滿父容器高度,第三欄維持 wrap_content,可以觀察兩者的差異。

<?xml version="1.0" encoding="utf-8"?>
<!--
    Demonstrates a horizontal linear layout with equally sized columns.
    Some columns force their height to match the parent.
-->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:background="@drawable/red"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_small"/>

    <TextView
        android:background="@drawable/green"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_big"/>

    <TextView
        android:background="@drawable/blue"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_small" />

    <TextView
        android:background="@drawable/yellow"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/linear_layout_7_wrap"/>
</LinearLayout>

這一系列範例帶走的三件事

Adapter 一定要複用 convertView。Grid2 那個 if-else 判斷看似微不足道,卻是長清單不卡頓的關鍵。

版面動畫有三種層次。用 Java 組 AnimationSet 交給 LayoutAnimationController(LayoutAnimation2)、在 XML 用 layoutAnimation 宣告(27~31)、或針對特定容器用 gridLayoutAnimation 控制傳播方向(29、30)。三者的表達力依次遞增,能純 XML 解決就不要寫 Java。

weight 與尺寸屬性的搭配有固定套路。要等分該軸向就寫 0dip + weight;要讓子元件撐滿父容器寬度則是父 wrap_content + 子 fill_parent;而 layout_gravity 想生效,容器的該軸向尺寸必須是 wrap_content。這幾條規則搞清楚了,多數版面問題都能直接判斷成因。

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