Android学习笔记_11_ListView控件使用

一、界面设计:

  1、activity_main.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"
    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=".MainActivity" >
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
    
        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="@string/name" />
          <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/age" />
    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp" >

    </ListView>

</RelativeLayout>
View Code

  2、item.xml文件:用于显示每一行的内容

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    
    <TextView
        android:id="@+id/name"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        />
      <TextView
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>
View Code

  3、最终测试界面:

  每行显示用户名称和年龄。

二、三种方式将数据绑定到ListView控件上:

package com.example.listview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.entity.Person;
import com.example.lservice.DBPersonService;
import com.example.lservice.PersonAdapter;

public class MainActivity extends Activity {

    private ListView listView;
    private DBPersonService personService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) this.findViewById(R.id.listView);
        personService = new DBPersonService(this);
      //监听行点击事件
listView.setOnItemClickListener(
new OnItemClickListener() { //parent:指当前被点击条目的listview view:指当前被点击的条目 position:被点击条目的索引 @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView lv = (ListView) parent; /* * 1、自定义适配器当前条目是Person对象。 * 2、采用SimpleCursorAdapter适配器,返回的是Cursor对象。 * 3、采用SimpleAdapter适配器,返回的是HashMap<String, Object>对象。 */ Person p = (Person) lv.getItemAtPosition(position); String info = p.getName() + " " + position + " " + id; Toast.makeText(getApplicationContext(), info, 1).show(); } }); show3(); } //第一种: 使用SimpleAdapter作为适配器 private void show() { List<Person> persons = personService.getScrollData(0, 20); List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (Person person : persons) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("name", person.getName()); map.put("age", person.getAge()); data.add(map); } SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,// 就是一个界面显示文件item.xml new String[] { "name", "age" },//from: 从结果集中获取数据,将需要显示的数据列名放到该集合 new int[] { R.id.name, R.id.age }// to:将结果集的数据字段对应到listview(item.xml)上 ); listView.setAdapter(adapter); } //第二种: 使用SimpleCursorAdapter作为适配器 private void show2() { Cursor cursor = personService.getCursorScrollData(0, 20); // 使用SimpleCursorAdapter适配器注意两个问题: // 1、返回的游标对象不能被关闭。 // 2、查询语句字段必须有"_id"这个字段,例如:select id as _id,name,age from person。 @SuppressWarnings("deprecation") SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, new String[] { "name", "age" }, new int[] { R.id.name, R.id.age }); listView.setAdapter(adapter); } //第三种: 自定义适配器PersonAdapter private void show3() { List<Person> persons = personService.getScrollData(0, 10); PersonAdapter adapter = new PersonAdapter(this, persons, R.layout.item); listView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }

 

  自定义适配器类实现:

package com.example.lservice;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.entity.Person;
import com.example.listview.R;

public class PersonAdapter extends BaseAdapter {
    //被绑定的数据
    private List<Person> persons;
    //绑定条目界面
    private int resource;
    //布局填充,作用是可以用xml文件生成View对象
    private LayoutInflater inflater;
    
    public PersonAdapter(Context context,List<Person> persons, int resource) {
        this.persons = persons;
        this.resource = resource;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return persons.size();
    }

    @Override
    public Object getItem(int position) {
        return persons.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    //会缓存之前的View
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView nameView =null;
        TextView ageView = null;
        if (convertView == null) {// 表示是第一页,需要创建该对象
            //生成条目界面对象
            convertView = inflater.inflate(resource, null);
             nameView = (TextView) convertView.findViewById(R.id.name);
             ageView = (TextView) convertView.findViewById(R.id.age);
            ViewCache cache = new ViewCache();
            cache.ageView=ageView;
            cache.nameView=nameView;
            //Tags can also be used to store data within a view without resorting to another data structure.
            convertView.setTag(cache);
        }else{
            ViewCache cache = (ViewCache) convertView.getTag();
            nameView = cache.nameView;
            ageView = cache.ageView;
        }
//        TextView nameView = (TextView) convertView.findViewById(R.id.name);
//        TextView ageView = (TextView) convertView.findViewById(R.id.age);
        Person person = persons.get(position);
        nameView.setText(person.getName());
        //setText方法:被设置的值要转换成字符串类型,否则出错
        ageView.setText(person.getAge().toString());
        
        return convertView;
    }
    /**
     * 由于每次都要查找View对象,因此就通过setTag将其保存起来。
     * @author Administrator
     *
     */
    private final class ViewCache{
        public TextView nameView;
        public TextView ageView;
        
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值