首页  >  文章  >  Java  >  如何在 Android 中使用静态标题和动态文本为 ListView 创建自定义行项目?

如何在 Android 中使用静态标题和动态文本为 ListView 创建自定义行项目?

Linda Hamilton
Linda Hamilton原创
2024-10-28 18:36:29235浏览

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.自定义适配器

创建一个扩展BaseAdapter的自定义适配器类:

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

    // ... implementation details ...
}</code>

4. Java Activity

在您的主要 Java 活动中,设置 ListView 和适配器:

<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>

预览

结果将是带有自定义行项目的 ListView显示所需的布局:

HEADER
Text

以上是如何在 Android 中使用静态标题和动态文本为 ListView 创建自定义行项目?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn