1. 程式人生 > >一步一步學android之控制元件篇——ListView自定義顯示資料格式

一步一步學android之控制元件篇——ListView自定義顯示資料格式

上一篇部落格說了ListView的基本使用,這篇將是對ListView的使用進行一個提高,在日常生活中,如果單單給你看一些圖片,你可能都不知道這個圖片表達的什麼意思,但是要是在圖片旁邊寫的備註或者加個名字,我們就會很清楚的知道這張圖片是什麼,所以就要使用到SimpleAdapter類了,下面用個例子來說明SImpleAdapter在ListView中的作用。

下面要實現的需求是,用ListView顯示9個女明星的照片,姓名和簡介,然後點選照片可以檢視原圖。

效果如下:


從上面的效果圖可以看出來這個ListView的項是包含了圖片和文字兩個物件的,所以我們需要先定義一個佈局檔案來作為顯示每一項的模板,listview_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" >

    <ImageView
        android:id="@+id/people"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="TextView" />

        <TextView
            android:id="@+id/introduce"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="TextView" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>

然後就是初始化ListView將資料加進去,在MainActivity中進行操作,MainActivity:
package com.example.listviewbasic;

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.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

	private ListView listView = null;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private SimpleAdapter simpleAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		listView = (ListView) super.findViewById(R.id.listView);
		settingAdapter();
		listView.setAdapter(simpleAdapter);
	}

	private void settingAdapter() {
		initList();
		// map中的key
		String from[] = new String[] { "people", "name", "introduce" };
		// 模板中的元件id
		int to[] = new int[] { R.id.people, R.id.name, R.id.introduce };
		simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item,
				from, to);
	}

	private void initList() {
		// 顯示的圖片資源
		int[] res = new int[] { R.drawable.liushishi, R.drawable.liushishi2,
				R.drawable.aiweier, R.drawable.aiweier2, R.drawable.piaoxinhui,
				R.drawable.piaoxinhui2, R.drawable.w, R.drawable.yuner,
				R.drawable.yuner2 };
		// 定義一個二維陣列來顯示姓名和簡介
		String string[][] = new String[][] { { "劉詩詩", "劉詩詩簡介" },
				{ "劉詩詩2", "劉詩詩2簡介" }, { "艾薇兒", "艾薇兒簡介" }, { "艾薇兒", "艾薇兒2簡介" },
				{ "樸信惠", "樸信惠簡介" }, { "樸信惠2", "樸信惠2簡介" }, { "樸信惠3", "樸信惠3簡介" },
				{ "允兒", "允兒簡介" }, { "允兒2", "允兒2簡介" }, };
		//初始化list資料
		for (int i = 0; i < 9; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("people", res[i]);
			map.put("name", string[i][0]);
			map.put("introduce", string[i][1]);
			list.add(map);
		}
	}
}

按照如上操作就可以實現上面第一張效果圖的效果,對程式碼的解釋我直接寫在程式碼中,下面實現點選圖片檢視原圖,我在這裡採用了popwindow,對於這個元件,後面也會有講,這裡就提前用下,同時我這裡為了效果感,還採用了動畫檔案,下面開始實現,首先是兩個動畫檔案pophidden_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- 透明度漸變 -->

    <scale
        android:duration="325"
        android:fillAfter="false"
        android:fromXScale="1"
        android:fromYScale="1"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.5"
        android:toYScale="1.5" >
    </scale>

    <alpha
        android:duration="400"
        android:fromAlpha="1"
        android:interpolator="@android:anim/linear_interpolator"
        android:toAlpha="0" />

</set>

popshow_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <scale
        android:duration="325"
        android:fillAfter="true"
        android:fromXScale="1.5"
        android:fromYScale="1.5"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" >
    </scale>

    <alpha
        android:duration="400"
        android:fromAlpha="0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toAlpha="1" />

</set>
然後是為點選顯示原圖加一個顯示佈局,show_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="#b0000000">

    <ImageView
        android:id="@+id/show_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>


接下來就是為ListView加OnItemClickListener事件,然後在裡面對檢視原圖的需求進行實現,修改後的MainActivity.java:
package com.example.listviewbasic;

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

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity implements OnItemClickListener {

	private ListView listView = null;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private SimpleAdapter simpleAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		listView = (ListView) super.findViewById(R.id.listView);
		settingAdapter();
		listView.setAdapter(simpleAdapter);
		listView.setOnItemClickListener(this);
	}

	private void settingAdapter() {
		initList();
		// map中的key
		String from[] = new String[] { "people", "name", "introduce" };
		// 模板中的元件id
		int to[] = new int[] { R.id.people, R.id.name, R.id.introduce };
		simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item,
				from, to);
	}

	private void initList() {
		// 顯示的圖片資源
		int[] res = new int[] { R.drawable.liushishi, R.drawable.liushishi2,
				R.drawable.aiweier, R.drawable.aiweier2, R.drawable.piaoxinhui,
				R.drawable.piaoxinhui2, R.drawable.w, R.drawable.yuner,
				R.drawable.yuner2 };
		// 定義一個二維陣列來顯示姓名和簡介
		String string[][] = new String[][] { { "劉詩詩", "劉詩詩簡介" },
				{ "劉詩詩2", "劉詩詩2簡介" }, { "艾薇兒", "艾薇兒簡介" }, { "艾薇兒", "艾薇兒2簡介" },
				{ "樸信惠", "樸信惠簡介" }, { "樸信惠2", "樸信惠2簡介" }, { "樸信惠3", "樸信惠3簡介" },
				{ "允兒", "允兒簡介" }, { "允兒2", "允兒2簡介" }, };
		//初始化list資料
		for (int i = 0; i < 9; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("people", res[i]);
			map.put("name", string[i][0]);
			map.put("introduce", string[i][1]);
			list.add(map);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		//點選list的item時獲取ImageView物件
		final ImageView img = (ImageView) view.findViewById(R.id.people);
		//設定單擊事件
		img.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					// 動態載入要用來顯示點選放大的圖片的佈局
					View show = LayoutInflater.from(MainActivity.this).inflate(
							R.layout.show_item, null);
					// 定義一個popwindow
					final PopupWindow pw = new PopupWindow(show,
							LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
							true);
					// 獲取show_item佈局中的ImageView id
					ImageView showImg = (ImageView) show
							.findViewById(R.id.show_img);
					// 將點選的圖片設定到showImg中
					showImg.setImageDrawable(img.getDrawable());
					// 點選螢幕關閉popwindow,這裡是不管點選螢幕上什麼地方都關閉
//					pw.setTouchInterceptor(new OnTouchListener() {
//
//						@Override
//						public boolean onTouch(View v, MotionEvent event) {
//							// TODO Auto-generated method stub
//							pw.dismiss();
//							return false;
//						}
//					});
					// 控制點選能正常關閉popwindow,這句話很重要。(去掉不能正常監聽返回鍵)
					pw.setBackgroundDrawable(new BitmapDrawable());
					// 設定區域外可獲取觸控事件
					pw.setOutsideTouchable(true);
					// 設定動畫
					pw.setAnimationStyle(R.style.mypopwindow_anim_style);
					// 居中
					pw.showAtLocation(v, Gravity.CENTER, 0, 0);
					pw.update();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}

最終效果就是效果圖那樣的效果,就寫到這裡了。