Android之 ListView(1)

ListView是Android中最常用的控件之一。

当有太多数据需要显示的时候,ListView就派上用场了。它允许用户通过滑动手指的方式,将数据滑入滑出界面。

一、最简单的ListView实现

1、修改布局文件。我们在activity_main.xml中加入空间ListView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lkb.listviewtest.MainActivity">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

2、回到MainActivity.java中。首先我们创建需要显示的数据。

private String[] fruit = {"apple","watermelon","mango","strawberry","pineapple","jujube","banana",
            "apple","watermelon","mango","strawberry","pineapple","jujube","banana"};

3、最后在代码中实现往ListView中添加数据。数组中的数据是无法直接传递给ListView的,我们需要借助适配器。

常用的适配器有ArrayAdapter,SimpleAdapter和SimpleCursorAdapter。这里使用ArrayAdapter。

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1,fruit);

这里我们获取了一个ArrayAdapter对象。ArrayAdapter的构造函数有六个。这个对应的是

/**
     * Constructor
     *
     * @param context The current context.
     * @param resource The resource ID for a layout file containing a TextView to use when
     *                 instantiating views.
     * @param objects The objects to represent in the ListView.
     */
    public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull T[] objects) {
        this(context, resource, 0, Arrays.asList(objects));
    }
android.R.layout.simple_list_item_1是Android内置的一个布局文件的id。这里我们使用它作为ListView中子项的布局。
最后通过ListView的setAdapter方法,将构建好的适配器对象传递进去,这样ListView和数据之间的关联就建立完成了。
  ListView listView = (ListView) findViewById(R.id.list_view);
  listView.setAdapter(adapter);

通过上面三步,我们就实现了ListView。



posted on 2017-03-02 10:55  猫咪大王  阅读(143)  评论(0编辑  收藏  举报