您的位置:首页 > 移动开发 > Android开发

Android开发从入门到放弃(8)使用ListView显示一个简单的列表

2016-12-28 10:29 741 查看
本篇博客简单介绍一下Android开发中ListView的使用,并显示一个简单列表,点击列表中的某一项时,会显示出该项的名称。在Android中,显示一个列表是比较容易的,我总结了下,只需三步

一个待显示的数据列表,可以是简单类型,也可以是自定义类型,

一个用于展示每一个数据项的模板,

根据前两项来一个Adapter对象,可以是ArrayAdapter、CursorAdapter或者自定义一个Adapter, 并将Adapter对象与ListView做关联

接下来我来做一个列子,用于展示一个简单的列表。下面是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.zdk.listview.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="select countries" />

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list"></ListView>
</RelativeLayout>


如果你想让Activity继承自ListActivity的话,可以不调用
setContentView()
来指定任何Layout,也可以指定一个Layout。如果指定Layout的话,则Layout中必须包含一个id为
@android:id/list
的ListView类型的控件。

下面是MainActivity.java的代码

package com.example.zdk.listview;

import android.app.ListActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

String[] countries = new String[]{"China", "France",
"Germany", "India", "Russia", "United Kingdom",
"United States"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListAdapter adapter  = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1,countries);
setListAdapter(adapter);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "你选择了"+countries[position] , Toast.LENGTH_SHORT).show();
}
}


按照上面所说的三步,第一个是创建了一个
countries
的数组,第二步是选择使用
android.R.layout.simple_expandable_list_item_1
作为每一项显示的模板,第三步是实例化了一个ArrayAdapter类型的adapter对象,并通过
setListAdapter(adapter);
与ListView设置了关联。

需要注意的是,MainActivity继承自ListActivity。我重写了ListActivity的
onListItemClick
方法,当用户点击某一项的时候,通过Toast显示点击的项的信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android listview
相关文章推荐