Android ListView示例教程

这篇教程介绍了Android ListView的基础知识,包括其定义、如何使用适配器填充数据,以及处理点击事件的方法。示例项目展示了如何创建一个简单的ListView,并在选择列表项时启动新活动。
摘要由CSDN通过智能技术生成

We will learn how to create a simple Android ListView and launch a new activity on selecting a single list item.

我们将学习如何创建一个简单的Android ListView并在选择单个列表项时启动新的活动。

什么是Android ListView? (What is Android ListView?)

Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database. It’s one of the basic and most used UI components of android. The most common usages include displaying data in the form of a vertical scrolling list.

Android ListView是将多个项目分组并在垂直滚动列表中显示的视图。 列表项是使用适配器从列表或数据库等源中自动提取内容的适配器自动插入列表中的。 它是android的基本和最常用的UI组件之一。 最常见的用法包括以垂直滚动列表的形式显示数据。

使用适配器 (Using an Adapter)

An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter holds the data and send the data to adapter view, the view can take the data from adapter view and shows the data on different views like as spinner, list view, grid view etc. The adapter pulls the items out of a data source, an array for example, and then converts each item into a view which it then inserts into the ListView.

适配器实际上是UI组件和将数据填充到UI组件中的数据源之间的桥梁。 适配器保存数据并将数据发送到适配器视图,该视图可以从适配器视图获取数据,并在不同的视图(例如微调器,列表视图,网格视图等)上显示数据。适配器将项目从数据源中拉出,例如一个数组,然后将每个项目转换为一个视图,然后将其插入到ListView中。

The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry. The common adapters are ArrayAdapter, BaseAdapter, CursorAdapter, SimpleCursorAdapter, SpinnerAdapter and WrapperListAdapter.

ListViewGridViewAdapterView子类,可以通过将它们绑定到Adapter来进行填充,该Adapter从外部源检索数据并创建一个表示每个数据条目的View。 常见的适配器是ArrayAdapter,BaseAdapter,CursorAdapter,SimpleCursorAdapter,SpinnerAdapter和WrapperListAdapter

处理Android ListView点击 (Handling Android ListView Clicks)

The onListItemClick() method is used to process the clicks on android ListView item. This method receives 4 parameters:

onListItemClick()方法用于处理对Android ListView项目的点击。 此方法接收4个参数:

  1. ListView : The ListView containing the item views

    ListView :包含项目视图的ListView
  2. View : The specific item view that was selected

    视图 :选择的特定项目视图
  3. Position : The position of the selected item in the array. Remember that the array is zero indexed, so the first item in the array is at position 0

    位置 :所选项目在数组中的位置。 请记住,数组的索引为零,因此数组的第一项位于位置0
  4. Id : The id of the selected item. Not of importance for our tutorial but is important when using data retrieved from a database as you can use the id (which is the id of the row containing the item in the database) to retrieve the item from the database

    ID :所选项目的ID。 对于我们的教程而言并不重要,但是在使用从数据库中检索到的数据时非常重要,因为您可以使用ID(数据库中包含该项目的行的ID)从数据库中检索项目

Android ListView示例项目结构 (Android ListView Example Project Structure)

Let’s begin with defining the string resources file to store all list item labels. So we create an XML file under values folder and name it as strings.xml and paste the following code.

让我们开始定义字符串资源文件以存储所有列表项标签。 因此,我们在values文件夹下创建一个XML文件,并将其命名为strings.xml并粘贴以下代码。

strings.xml

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="teams">
        <item>India</item>
        <item>South Africa</item>
        <item>Australia</item>
        <item>England</item>
        <item>New Zealand</item>
        <item>Sri Lanka</item>
        <item>Pakistan</item>
        <item>West Indies</item>
        <item>Bangladesh</item>
        <item>Ireland</item>
    </string-array>
</resources>

Each list view item will be represented by an xml layout,so lets define the xml layout comprising of a single textview as follows:

每个列表视图项将由一个xml布局表示,因此让我们定义一个包含单个textview的xml布局,如下所示:

list_item.xml

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold" >
</TextView>

Following snippet shows how to import the xml resources data and store them in data followed by binding them to the adapter:

以下片段显示了如何导入xml资源数据并将其存储在数据中,然后将它们绑定到适配器:

// storing string resources into Array
String[] teams = getResources().getStringArray(R.array.teams);

// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.textview, teams));

In the following code we fetch the data value from the selected item and pass it as a bundle to the next activity using intents.

在下面的代码中,我们从选定的项目中获取数据值,然后将其作为数据包使用intent传递给下一个活动。

MainActivity.java

MainActivity.java

package journaldev.com.listview;


import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // storing string resources into Array
        String[] teams = getResources().getStringArray(R.array.teams);

        // Binding resources Array to ListAdapter
        this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.textview, teams));

        ListView lv = getListView();

        // listening to single list item on click
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // selected item 
                String team = ((TextView) view).getText().toString();

                // Launching new Activity on selecting single List Item
                Intent i = new Intent(getApplicationContext(), SecondActivity.class);
                // sending data to new activity
                i.putExtra("team", team);
                startActivity(i);

            }
        });
    }
}

The SecondActivity class retrieves the text label from the list item selected and displays it in a textview as shown in the following snippet.

SecondActivity类从选定的列表项中检索文本标签,并将其显示在textview中,如以下代码片段所示。

SecondActivity.java

SecondActivity.java

package journaldev.com.listview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        TextView txtProduct = (TextView) findViewById(R.id.team_label);

        Intent i = getIntent();
        // getting attached intent data
        String product = i.getStringExtra("team");
        // displaying selected product name
        txtProduct.setText(product);
    }
}

Following small GIF depict the flow of the app:

android-listview-example

以下小GIF描述了应用程序的流程:

That’s all for a quick android listview example. You should also learn about Expandable ListView. You can download android list view project from below link.

这就是一个快速的Android listview示例的全部。 您还应该了解Expandable ListView 。 您可以从下面的链接下载android list view项目

翻译自: https://www.journaldev.com/9247/android-listview-example-tutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值