Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 開發入門:ListView 與 LinearLayout 佈局解析

學習 Android 介面開發,第一個繞不開的就是佈局檔。本文以一個最典型的範例出發:先寫好列表項的外觀,再交給 ListView 去反覆填充。

先看列表項的佈局檔

新增一個名為 frame.xml 的檔案,內容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="1pt"
    android:paddingLeft="1pt"
    android:paddingRight="10pt"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/appname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="15pt" />

</LinearLayout>

這個檔案稍後會被 Activity 透過 setContentView() 載入,也可以作為 ListView 的項目範本使用。

幾個關鍵屬性的含義

android:orientation

決定 LinearLayout 內部子元件的排列方向。填 vertical 就是由上而下縱向堆疊,填 horizontal 則是由左而右橫向排列。本例使用橫向,因此 TextView 會從左側開始佔滿剩餘寬度。

android:drawSelectorOnTop

這個屬性用來控制「被選中時的高亮效果」要畫在內容之上,還是畫在內容之下。

設為 false:selector 在底層,文字、圖片等內容會蓋住高亮色,視覺上更清晰,多數情況推薦這種寫法。

設為 true:selector 蓋在最上層,整齊地被染成一塊色塊,但底下的內容會被遮掉一部分。

padding 與 textSize

paddingTop / paddingLeft / paddingRight 描述的是「內容與邊界之間的留白」,單位可用 pt、dp 或 dip。而 textSize 決定文字大小,早期專案常見 pt 寫法,新專案建議改用 sp,才能跟隨使用者的系統字級設定。

小結

把項目佈局寫好之後,真正讓列表「活起來」的關鍵在於 Adapter:它負責把資料一份份塞進這個範本,並在元件被回收重複使用時重新綁定內容。理解佈局與 Adapter 的分工,是 ListView 學習路上一大步。

Copyright © Linux教程網 All Rights Reserved