首页  >  文章  >  Java  >  如何在 Android ListView 中自定义行项目:分步指南?

如何在 Android ListView 中自定义行项目:分步指南?

Barbara Streisand
Barbara Streisand原创
2024-10-29 04:22:02987浏览

How to Customize Row Items in an Android ListView: A Step-by-Step Guide?

为 Android ListView 创建自定义行项目:详细指南

在本文中,我们将探讨如何创建自定义行项目对于 Android 应用程序中的 ListView。

挑战

我们有一个 ListView,需要具有以下布局的行:

HEADER
Text

“HEADER”文本保持静态,而“Text”内容动态变化。

初始方法

最初,我们尝试填充一个字符串数组,将其传递给ArrayAdapter,并在每次数据更改时设置它:

data_array = populateString();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1,  data_array);
listView.setAdapter(adapter);

但是,这种方法没有提供期望的结果,因为现有布局无法以指定格式显示数据。

自定义行布局

为了克服此限制,我们将为行项目创建自定义布局:

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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"/>
    
</LinearLayout></code>

主要 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" >
    </ListView>

</LinearLayout></code>

适配器

我们现在定义适配器:

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

    // ... (the adapter code) ...
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // ... (customizing view) ...
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}</code>

Java Activity

最后,在 Java 活动中:

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

    // ... (the activity code) ...
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ... (setting up listview) ...
        listview.setAdapter(new yourAdapter(this, new String[] { "data1", "data2" }));
    }
}</code>

通过执行以下步骤,您可以为 ListView 创建自定义行项目,从而在数据呈现方面提供更大的灵活性和自定义性。

以上是如何在 Android ListView 中自定义行项目:分步指南?的详细内容。更多信息请关注PHP中文网其他相关文章!

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