现在的位置: 首页 > 移动开发 > 正文

Android实战开发二,ListView组件应用,适配器的三种效用

2019年10月11日 移动开发 ⁄ 共 12045字 ⁄ 字号 评论关闭

Android中进行想进行数据列表,必须要用到ListView列表组件,该组件可以将一组数据,循环列表显示到界面上,并自带滚动功能。

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

使用时,也要通过Adapter来动态加入数据,根据表格的格式,需要选择不同的Adapter来完成。

如果表格一行中只有一段字符串,没有进行格式处理,可以使用ArrayAdapter例如:

public class MainActivity extends Activity {

	private List<String> allValues = new ArrayList<String>();

	private ArrayAdapter<String> adapter;

	private ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置所使用的布局界面
		setContentView(R.layout.activity_main);

		// 取得组件
		list = (ListView) findViewById(R.id.list);

		// 初始化要添加到表格中的数据
		for (int i = 0; i < 50; i++) {
			allValues.add("添加的数据" + i);
		}

		// 建立Adapter
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, allValues);

		list.setAdapter(adapter);

	}
}

 

如果表格中每一行的数据格式比较复杂,但是里面没有图片,可以使用SimpleAdapter来实现,例如:

如果没有图片显示,可以使用SimpleAdapter处理复杂格式。

使用这个Adapter之前,需要先编写一个layout下的xml布局文件,描述每一行的布局格式

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="horizontal"
    android:paddingBottom="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="5dp" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/line_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#66cdaa"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/line_time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#cccccc"
            android:textSize="10sp" />

        <TextView
            android:id="@+id/line_area"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#cccccc"
            android:textSize="10sp" />
    </LinearLayout>

    <TextView
        android:id="@+id/line_price"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:textColor="#FF6600"
        android:textSize="12sp" />

</LinearLayout>

在程序中,建立SimpleAdapter,读取这个布局,并将数据与布局中的TextView组件绑定。

public class MainActivity extends Activity {

	// 由于每一行数据所对应的数据量不再是一条,而是多条,而且要根据名称进行区分,所以List中每一条数据是一个Map集合.
	private List<Map<String, Object>> allValues = new ArrayList<Map<String, Object>>();

	private SimpleAdapter adapter;

	private ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置所使用的布局界面
		setContentView(R.layout.activity_main);

		// 取得组件
		list = (ListView) findViewById(R.id.list);

		// 初始化要添加到表格中的数据
		for (int i = 0; i < 50; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("title", "商品标题信息 " + i);
			map.put("time", "9成新  " + i + "小时前发布");
			map.put("area", "江苏 南通");
			map.put("price", (int) (Math.random() * 1000) + "元");

			allValues.add(map);
		}

		// 建立Adapter
		adapter = new SimpleAdapter(this, allValues,
				R.layout.simple_adapter_list_line, new String[] { "title",
						"time", "area", "price" }, new int[] { R.id.line_title,
						R.id.line_time, R.id.line_area, R.id.line_price });

		list.setAdapter(adapter);

	}
}

通过属性,可以控制分隔线的颜色

<ListView
        android:id="@+id/list"
        android:divider="#dddddd"
        android:cacheColorHint="#00000000"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
</ListView>

//cacheColorHint是为了防止滚动时屏幕闪烁加入的配置。

 

如果每行中还有图片显示,则要自定义Adapter来完成,例如:(这边详细说明)

第一步,编写的是布局layout.xml

<LinearLayout 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:orientation="vertical"
    android:background="#FFFFFF">

    
    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal"
    android:background="@drawable/header_bg"
       >
    	<TextView 
        	android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@drawable/back_btn"
            android:layout_weight="1"
            />
    	<TextView 
    	    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:layout_weight="3.8"
    	    />
    	<TextView 
    	    android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:textColor="#FFFFFF"
            android:text="找设备"
            android:textSize="15sp"
            android:layout_weight="2"
    	    />
    	<TextView 
    	    android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text=""
            android:layout_weight="4.2"
    	    />
    </LinearLayout>
    
    <!-- 
    	这是中间的部分
     -->
    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="12.5"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
       >
        <LinearLayout 
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:orientation="vertical"
            >
            <Button 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/phone01_a"
                />
            <Button 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/phone02_a"
                />
            <Button 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/phone03_a"
                />
            <Button 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/phone04_a"
                />
        </LinearLayout>
        
        <!-- 
        	这是中间右边的部分ListView,这里的高度不能写死,前两行是设置滑动线的
         -->
	     <ListView
	        android:id="@+id/list"
	        android:divider="#dddddd"
	        android:cacheColorHint="#00000000"
	        android:scrollbars="none"
	        android:layout_width="0dp"
	        android:layout_weight="4.82"
	        android:layout_height="wrap_content" >
	     </ListView>

    </LinearLayout>
    
    <!-- 
    	这是底部
     -->
    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1.5"
    android:background="#000000"
    android:orientation="horizontal"
       >
        <Button 
            android:id="@+id/buttom01_btn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/buttom_btn01"
            />
        <Button 
            android:id="@+id/buttom02_btn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/buttom_btn02"
            />
        <Button
            android:id="@+id/buttom03_btn" 
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/buttom_btn03"
            />
        <Button 
            android:id="@+id/buttom04_btn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/buttom_btn04"
            />
        <Button 
            android:id="@+id/buttom05_btn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/buttom_btn05"
            />
    </LinearLayout>
 

</LinearLayout>

布局后的预览:

第二步:编写是处理列表的数据的

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"  
      android:layout_height="wrap_content"
      android:layout_marginLeft="5dp"
      android:layout_marginRight="5dp"
      android:orientation="horizontal" >

            <TextView 
                android:id="@+id/line_img"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.5"
                android:background="@drawable/phone_content"
                />
            <!-- 
            	这是右侧字体的部分
             -->
            <LinearLayout 
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:orientation="vertical"
                >
             	<TextView
             	android:id="@+id/line_phonename" 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#000000"
                android:textSize="12sp"
                />
             	<TextView 
             	android:id="@+id/line_os"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#cccccc"
                android:textSize="10sp"
                />
             	<TextView 
             	android:id="@+id/line_screen"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#cccccc"
                android:textSize="10sp"
                />
             	<TextView
             	android:id="@+id/line_resolution"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#cccccc"
                android:textSize="10sp"
                />
             	<Button 
             	    android:id="@+id/line_detail"
             	    android:layout_width="wrap_content"
             	    android:layout_height="wrap_content"
             	    android:background="@drawable/detail_img"
             	    />
            </LinearLayout> 
             <TextView 
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:text=""
                />
</LinearLayout>

这里的界面是靠数据来填充的,所以我们只编写了一行数据然后通过适配器循环的排列出来,我们先编写好MainActivity

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import cn.itcast.finddvice.adapter.deviceAdapter;
import cn.itcast.finddvice.util.Globals;

public class MainActivity extends Activity {

	// 由于每一行数据所对应的数据量不再是一条,而是多条,而且要根据名称进行区分,所以List中每一条数据是一个Map集合.
	
	private List<Map<String, Object>> allValues = new ArrayList<Map<String, Object>>();

	private deviceAdapter adapter;

	private ListView list;

	// 将所有图片放到一个数组中
	private int[] allImgs = {R.drawable.phone_content,
			R.drawable.detail_img};
	
	private Button buttom01_btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
     
     //根据屏幕初始化配置确定每一ListView相对大小
        Globals.init(this);
     //取得组件
        list = (ListView) findViewById(R.id.list);
        
     // 初始化要添加到表格中的数据
        for(int i=0;i<50;i++){
        	Map<String,Object> map = new HashMap<String, Object>();
        	map.put("name", "HTC A310e 3G手机" + i);
        	map.put("os","Android2.3");
        	map.put("screen", "屏幕尺寸:3.2英寸");
        	map.put("resolution", "分辨率:320*480");
        	map.put("imgphone", allImgs[0]);
        	map.put("imgdetail",allImgs[1]);
        	
        	allValues.add(map);
        }
        
     // 建立Adapter
        adapter = new deviceAdapter(this, allValues);
        
        list.setAdapter(adapter);

然后编写适配器:deviceAdapter

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import cn.itcast.finddvice.R;
import cn.itcast.finddvice.util.Globals;

public class deviceAdapter extends BaseAdapter {

	private Context ctx;
	private List<Map<String,Object>> allValues;
	//构造方法
	public deviceAdapter(Context ctx, List<Map<String, Object>> allValues) {
		this.ctx = ctx;
		this.allValues = allValues;
	}

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

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

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		// 设置每一行的显示界面和内容.
		// 判断当前行的组件之前是否建立过,如果建立过,直接改变数据内容即可,如果没有建立过,则需要自己建立.
		if(convertView == null){
			// 还没有建立,需要手工建立
			// 建立行时,需要根据写好的布局来建立
			convertView = LayoutInflater.from(ctx).inflate(R.layout.phone_list, null);
			
			// 设置行的高度,这是根据手机屏幕大小计算的
			//注意这里导包:import android.widget.AbsListView.LayoutParams;
			convertView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					Globals.SCREEN_HEIGHT/6));
		}
		
		// 从读取到的行布局中,取得每一个组件
		TextView imgText = (TextView) convertView.findViewById(R.id.line_img);
		imgText.getLayoutParams().height = Globals.SCREEN_HEIGHT / 6;
		
		TextView nameText = (TextView) convertView.findViewById(R.id.line_phonename);
		TextView osText = (TextView) convertView.findViewById(R.id.line_os);
		TextView screenText = (TextView) convertView.findViewById(R.id.line_screen);
		TextView resolution = (TextView) convertView.findViewById(R.id.line_resolution);
		Button detailbtn = (Button) convertView.findViewById(R.id.line_detail);
		
		// 取得当前行的数据
		Map<String,Object> map = allValues.get(position);
		nameText.setText(map.get("name").toString());
		osText.setText(map.get("os").toString());
		screenText.setText(map.get("screen").toString());
		resolution.setText(map.get("resolution").toString());
		
		// 图片处理
		imgText.setBackgroundResource((Integer) map.get("imgphone"));
		detailbtn.setBackgroundResource((Integer) map.get("imgdetail"));
		return convertView;
	}

}

//上面适配器以及之前的MainActivity中的Globals这个类,是一计算手机频幕大小的公共类

import android.app.Activity;

public class Globals {
	
	public static int SCREEN_WIDTH;
	public static int SCREEN_HEIGHT;
	
	public static void init(Activity a){
		
		SCREEN_WIDTH = a.getWindowManager().getDefaultDisplay().getWidth();
		SCREEN_HEIGHT = a.getWindowManager().getDefaultDisplay().getHeight();
	}
}

项目:

最后项目在模拟器下的显示效果:

 

 

抱歉!评论已关闭.