安卓 使用Adapter(适配器)填充ListView(列表)

安卓 使用Adapter(适配器)填充ListView(列表)

一、简述

      记--简单的使用Adapter(适配器)填充ListView(列表)。

      

      例子打包:链接: https://pan.baidu.com/s/1QT3WBh033RWaz3KJYw2L2g 提取码: 4h99  (包含3个例子)

二、例子1--直接使用ArrayAdapter<>适配器

       将多个书籍名称显示到ListView。

      效果:

                                       

      工程结构:

      代码:

      MainActivity.java文件

package com.liang.adapter;

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

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.annotation.SuppressLint;
import android.app.Activity;

@SuppressLint("NewApi") 
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //准备数据 (这里直接写死,一般可以从数据库等相关数据文件中获取)
        List<String> bookList = new ArrayList<String>();
        bookList.add("红楼梦");
        bookList.add("西游记");
        bookList.add("水浒传");
        bookList.add("三国演义");
        
        //1 new一个适配器,并且将数据项的布局文件为R.layout.book_item
        ArrayAdapter<String> bookAdapter = new ArrayAdapter<String>(this, R.layout.book_item);
        
        //2 设置ListView的适配器
        ListView lv_books = (ListView)findViewById(R.id.lv_books);
        lv_books.setAdapter(bookAdapter);
        
        //3 设置Adapter的数据源
        bookAdapter.addAll(bookList);
        bookAdapter.add("Android那些事");//再添加一个数据
    }
}

布局文件

activity_main.xml文件  (有个ListView列表控件)

<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" >

    <ListView
        android:id="@+id/lv_books"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

book_item.xml文件   (用来显示数据项)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:padding="5dp" />

在此基础上添加数据项的点击响应 

效果:

                                   

修改后的代码:MainActivity.java文件

package com.liang.adapter;

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

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;

@SuppressLint("NewApi") 
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //准备数据 (这里直接写死,一般可以从数据库等相关数据文件中获取)
        List<String> bookList = new ArrayList<String>();
        bookList.add("红楼梦");
        bookList.add("西游记");
        bookList.add("水浒传");
        bookList.add("三国演义");
        
        //1 new一个适配器,并且将数据项的布局文件为R.layout.book_item
        ArrayAdapter<String> bookAdapter = new ArrayAdapter<String>(this, R.layout.book_item);
        
        //2 设置ListView的适配器
        ListView lv_books = (ListView)findViewById(R.id.lv_books);
        lv_books.setAdapter(bookAdapter);
        
        //3 设置Adapter的数据源
        bookAdapter.addAll(bookList);
        bookAdapter.add("Android那些事");//再添加一个数据
        
        //4 设置ListView数据项点击监听者   (设置点击某个数据项后的处理动作)
        lv_books.setOnItemClickListener(itemClickListener);
    }
    
    //数据项点击监听者(当数据项被点击时,)
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            //点击后的动作响应
            String bookName = ((TextView) v).getText().toString();// 获取点击的书籍的名称
            Toast.makeText(MainActivity.this, bookName, Toast.LENGTH_SHORT).show();//弹出提示框
        }
    };
}

三、例子2--自定义适配器

        将多个书籍名称,作者显示到ListView。

       效果:

                                       

       代码结构:

       代码文件:

MainActivity.java文件

package com.liang.adapter;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;

@SuppressLint("NewApi") 
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //准备数据 (这里直接写死,一般可以从数据库等相关数据文件中获取)
        List<Book> bookList = new ArrayList<Book>();
        bookList.add( new Book("红楼梦", "曹雪芹") );
        bookList.add( new Book("西游记", "吴承恩") );
        bookList.add( new Book("水浒传", "施耐庵") );
        bookList.add( new Book("三国演义", "罗贯中") );
        
        //1 new一个适配器,并且将数据项的布局文件为R.layout.book_item
        BookListAdapter bookAdapter = new BookListAdapter(this, R.layout.book_item);
        
        //2 设置ListView的适配器
        ListView lv_books = (ListView)findViewById(R.id.lv_books);
        lv_books.setAdapter(bookAdapter);
        
        //3 设置Adapter的数据源
        bookAdapter.addAll(bookList);
        bookAdapter.add(new Book("Android那些事", "安卓") );//再添加一个数据
        
        //4 设置ListView数据项点击监听者   (设置点击某个数据项后的处理动作)
        lv_books.setOnItemClickListener(itemClickListener);
    }
    
    //数据项点击监听者(当数据项被点击时,)
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            //点击后的动作响应
        	TextView tv_name = (TextView)v.findViewById(R.id.book_name);
        	TextView tv_author = (TextView)v.findViewById(R.id.book_author);
        	
            String bookName = tv_name.getText().toString();// 获取点击的书籍的名称
            String bookAuthor = tv_author.getText().toString();// 获取点击的书籍的作者
            
            Toast.makeText(MainActivity.this, "书名:"+bookName+"\n作者:"+bookAuthor, Toast.LENGTH_SHORT).show();//弹出提示框
        }
    };
    
    //定义书类
    public class Book
    {
    	public String name;//书名字段
    	public String author;//书的作者字段
    	
    	//构造函数
    	Book(String name, String author)
    	{
    		this.name = name;
    		this.author = author;
    	}
    }
    
    //自定义适配器
    public class BookListAdapter extends ArrayAdapter<Book>
    {
    	private Context context;
    	private int resource;

		public BookListAdapter(Context context, int resource) {
			super(context, resource);
			this.context = context;
			this.resource = resource;
		}
		
		@Override
	    public View getView(int position, View convertView, ViewGroup parent) {

	        if (convertView == null) 
	        {
	        	//设置数据项的布局样式
	            convertView = LayoutInflater.from(context).inflate(resource, parent, false);
	        }

	        //获取数据项布局里面的TextView句柄
	        TextView bookName = (TextView) convertView.findViewById(R.id.book_name);
	        TextView author = (TextView) convertView.findViewById(R.id.book_author);

	        //获取点击的数据项信息
	        Book book = getItem(position);
	        
	        //将数据项信息填充到TextView
	        bookName.setText(book.name);
	        author.setText(book.author);
	        
	        return convertView;
	    }
    }
}

布局文件(其它的与例子1一样)

book_item.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="58dp"
    android:padding="5dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/book_name"
        android:gravity="center_vertical"
        android:textColor="#000"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/book_author"
        android:gravity="center_vertical|right"
        android:textColor="#000"/>

</LinearLayout>

四、例子3-自定义适配器( 通过构造函数传递数据)

      效果:

                                        

                                    

     工程结构:

     代码文件:

MainActivity.java文件

package com.liang.adapter;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;

@SuppressLint("NewApi") 
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //准备数据 (这里直接写死,一般可以从数据库等相关数据文件中获取)
        List<Book> bookList = new ArrayList<Book>();
        bookList.add( new Book(R.drawable.hongloumeng, "红楼梦", "曹雪芹") );
        bookList.add( new Book(R.drawable.xiyouji, "西游记", "吴承恩") );
        bookList.add( new Book(R.drawable.shuihuzhuan, "水浒传", "施耐庵") );
        bookList.add( new Book(R.drawable.sanguoyanyi, "三国演义", "罗贯中") );
        
        //1 new一个适配器,并且将数据项的布局文件设置为R.layout.book_item,数据源为bookList
        BookListAdapter bookAdapter = new BookListAdapter(this, R.layout.book_item, bookList);
        
        //2 设置ListView的适配器
        ListView lv_books = (ListView)findViewById(R.id.lv_books);
        lv_books.setAdapter(bookAdapter);
        
        //3 设置ListView数据项点击监听者   (设置点击某个数据项后的处理动作)
        lv_books.setOnItemClickListener(itemClickListener);
        
    }
    
    //数据项点击监听者(当数据项被点击时,)
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            //点击后的动作响应
        	TextView tv_name = (TextView)v.findViewById(R.id.tv_bookName);
        	TextView tv_author = (TextView)v.findViewById(R.id.tv_bookAuthor);
        	
            String bookName = tv_name.getText().toString();// 获取点击的书籍的名称
            String bookAuthor = tv_author.getText().toString();// 获取点击的书籍的作者
            
            Toast.makeText(MainActivity.this, "书名:"+bookName+"\n作者:"+bookAuthor, Toast.LENGTH_SHORT).show();//弹出提示框
        }
    };
    
    //定义书类
    public class Book
    {
    	public int image;//书籍图片
    	public String name;//书名字段
    	public String author;//书的作者字段
    	
    	//构造函数
    	Book(int image, String name, String author)
    	{
    		this.image = image;
    		this.name = name;
    		this.author = author;
    	}
    }
    
    //自定义适配器
    public class BookListAdapter extends BaseAdapter
    {
    	private List<Book> bookList;
    	private Context context;
    	private int resource;

		public BookListAdapter(Context context, int resource, List<Book> bookList) {
			this.context = context;
			this.resource = resource;
			this.bookList = bookList;
		}
		
		@Override
	    public View getView(int position, View convertView, ViewGroup parent) {

	        if (convertView == null) 
	        {
	        	//设置数据项的布局样式
	            convertView = LayoutInflater.from(context).inflate(resource, parent, false);
	        }

	        //获取数据项布局里面的ImageView,TextView句柄
	        ImageView imageView = (ImageView)convertView.findViewById(R.id.book_image);
	        TextView bookName = (TextView) convertView.findViewById(R.id.tv_bookName);
	        TextView author = (TextView) convertView.findViewById(R.id.tv_bookAuthor);

	        //获取点击的数据项信息
	        Book book = bookList.get(position);
	        
	        //将数据项信息填充到imageView,TextView
	        imageView.setImageResource(book.image);
	        bookName.setText("《"+book.name+"》");
	        author.setText("作者:"+book.author);
	        
	        return convertView;
	    }

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

		@Override
		public Object getItem(int index) {
			return bookList.get(index);
		}

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

R.java文件 (创建工程自带的配置文件)

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.liang.adapter;

public final class R {
    public static final class attr {
    }
    public static final class dimen {
        public static final int activity_horizontal_margin=0x7f040000;
        public static final int activity_vertical_margin=0x7f040001;
    }
    public static final class drawable {
        public static final int defaultpic=0x7f020000;
        public static final int hongloumeng=0x7f020001;
        public static final int ic_launcher=0x7f020002;
        public static final int sanguoyanyi=0x7f020003;
        public static final int shuihuzhuan=0x7f020004;
        public static final int xiyouji=0x7f020005;
    }
    public static final class id {
        public static final int book_image=0x7f070001;
        public static final int lv_books=0x7f070000;
        public static final int tv_bookAuthor=0x7f070003;
        public static final int tv_bookName=0x7f070002;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
        public static final int book_item=0x7f030001;
    }
    public static final class string {
        public static final int action_settings=0x7f050001;
        public static final int app_name=0x7f050000;
        public static final int hello_world=0x7f050002;
    }
    public static final class style {
        public static final int AppBaseTheme=0x7f060000;
        public static final int AppTheme=0x7f060001;
    }
}

 

布局文件:

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" >

    <ListView
        android:id="@+id/lv_books"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

                                                                                      

book_item.xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/book_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@drawable/defaultpic" />

    <TextView
        android:id="@+id/tv_bookName"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_toEndOf="@+id/book_image"
        android:textSize="15sp"
        android:gravity="center_vertical|left"
        />

    <TextView
        android:id="@+id/tv_bookAuthor"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_toEndOf="@+id/book_image"
        android:layout_below="@+id/tv_bookName"
        android:textSize="15sp"
        android:gravity="center_vertical|left"
        />

</RelativeLayout>

                                                                                

 

五、总结

 1、遇到问题"Unparsed aapt error(s)! Check the console for output."  

        原因:资源文件夹res下的图片名字有大写,(含有特殊字符'_' 之类的也会导致)

        解决办法:将大写改为小写。

 

  • 5
    点赞
  • 1
    评论
  • 6
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页