首頁 > Java > java教程 > 主體

如何在 Android 中使用靜態標題和動態文字為 ListView 建立自訂行項目?

Linda Hamilton
發布: 2024-10-28 18:36:29
原創
237 人瀏覽過

How to Create Custom Row Items for a ListView in Android with a Static Header and Dynamic Text?

ListView 的Android 自訂行項目

概述

本文將展示如何在Android 中為ListView 建立自訂行項目,讓您能夠能夠以特定格式顯示資料。

挑戰

目標是建立一個 ListView,其中每一行都遵循特定的佈局:

HEADER
Text
登入後複製
登入後複製

HEADER 應保持靜態,而文字會定期變更。

解決方案

1.自訂佈局XML

將以下row.xml 加入到您的版面配置資料夾:

<code class="xml"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Header" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
</LinearLayout></code>
登入後複製

2.主XML 版面配置

更新主XML 版面配置以包含ListView:

<code class="xml"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
    
    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    
</LinearLayout></code>
登入後複製

3.自訂適配器

3.自訂適配器

<code class="java">class yourAdapter extends BaseAdapter {

    // ... implementation details ...
}</code>
登入後複製

建立一個擴充BaseAdapter的自訂適配器類別:

4. Java Activity
<code class="java">public class StackActivity extends Activity {

    ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... implementation details ...
        listview.setAdapter(new yourAdapter(this, new String[] { "data1", "data2" }));
    }
}</code>
登入後複製

在您的主要Java 活動中,設定和適配器:

HEADER
Text
登入後複製
登入後複製
預覽結果將是帶有自訂行項目的ListView顯示所需的佈局:

以上是如何在 Android 中使用靜態標題和動態文字為 ListView 建立自訂行項目?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!