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

Android 自訂 ListView 圓角背景

編輯:Android 開發實例

需求說明

預設的 ListView 背景通常是矩形,若希望畫面更柔和,可以透過 shape drawable 自訂圓角背景。這種做法不需要額外繪圖,只要定義 XML 資源即可。

建立 ListView

String[] mStrings = { "aaaa", "bbbb", "cccc" };

ListView listView = findViewById(R.id.list);
listView.setAdapter(new ArrayAdapter<String>(
    this,
    android.R.layout.simple_list_item_1,
    mStrings
));

套用背景資源

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@layout/list_corner_1"
    android:layout_weight="1.0" />

其中 list_corner_1.xml 定義圓角與漸層:

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#CCCCFF"
        android:endColor="#99CCFF"
        android:angle="90" />
    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />
</shape>

注意事項

若 ListView 項目本身有背景色,可能會覆蓋外層圓角效果。此時可將 item 背景設為透明,或改用 CardView、MaterialCardView 等元件實作更現代的卡片式列表。

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