本篇主要是使用系统ListView进行String类型数据的显示以及点击事件的处理
首先贴出我的xml布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ListView
android:id="@+id/lv_normal"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
xml布局很简单,在RelativeLayout中添加了一个充满整个屏幕的ListView控件
下面是MainActivity中的相关代码:
package com.jokerx.mylistview.activity;
import java.util.ArrayList;
import com.jokerx.mylistview.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class NormalListView extends Activity {
private ListView mLsitView;
private ArrayList<String> nameList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_list_view);
initView();
initData();
//用系统自带的Adapter来进行显示
mLsitView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, nameList));
mLsitView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mLsitView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("parent", parent + "");
Log.e("view", view + "");
Log.e("position", position + "");
Log.e("id", id + "");
}
});
}
private void initData() {
String name = "张三";
nameList = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
nameList.add(name + i);
}
}
private void initView() {
mLsitView = (ListView) findViewById(R.id.lv_normal);
}
}
首先初始化界面显示,在这里我用循环制造了10个数据,封装到一个ArrayList中。最主要的步骤就是为ListView设置Adapter适配器。这里我直接new了一个系统自带的ArrayAdapter,其中有三个参数,分别是 context:上下文, resource:具体显示的item的资源id, objects:具体的数据,官方的注释如下:
context The current context.
resource The resource ID for a layout file containing a TextView to use when instantiating views.
objects The objects to represent in the ListView.
Android自带了几种item的显示外观,可在resource处进行更改,在Demo中我用的是一个带有选择框的item来进行显示,在采用这个item的时候,必须要设置
mLsitView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
这条属性,否则点击之后item不会产生变化。
然后是item点击事件:有四个属性。分别是parent 是所用ListView的信息, view 是点击的Adapter中具体的View,可以对view进行相关的操作, position 所用adapter中的哪一项项,编号从0开始, id 是ListView 中对应的哪一项,编号从0开始
官方的注释如下:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position The position of the view in the adapter.
id The row id of the item that was clicked.
下章将研究自定义ListView以及自定义Adapter的知识。