控件ListView是一个重要的控件,可以被用作用户列表等显示,下面进行它的操作测试。
下面代码实现了生成了一个ListView显示,并对每个条目的单击事件作出响应.
源代码:
package com.list;
import java.util.ArrayList;
import java.util.HashMap;
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.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListTest extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, Object>> users = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 20; i++) {
HashMap<String, Object> user = new HashMap<String, Object>();
user.put("img", R.drawable.icon);
user.put("username", "姓名(" + i+")");
user.put("age", (20 + i) + "");
users.add(user);
}
SimpleAdapter saImageItems = new SimpleAdapter(this,
users,// 数据来源
//R.layout.user,//每一个user xml 相当ListView的一个组件
R.layout.user_layout,//每一个user xml 相当ListView的一个组件
new String[] { "img", "username", "age" },
// 分别对应view 的id
new int[] { R.id.img, R.id.name, R.id.age });
//获取适配器
ListView listView = (ListView) findViewById(R.id.users);
listView.setAdapter(saImageItems);
listView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id)
{
ListView listView = (ListView) parent;
Log.v("Test", "id = " + id + "("+ listView.getItemAtPosition(position).toString() + ")");
}
});
/*
listView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,View view,int position,long id)
{
ListView listView = (ListView) parent;
Log.v("Test", "id = " + id + "("+ listView.getItemAtPosition(position).toString() + ")");
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
*/
}
}
效果图:
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/androidbc/2655.html