1. 程式人生 > >Android開發入門之採用ListView實現資料列表顯示

Android開發入門之採用ListView實現資料列表顯示

再次用到上一篇寫過的db工程,

activity_main.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:background="@android:color/black"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="@string/name"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="@string/phone"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="@string/amount"
            android:textColor="@android:color/white"
            android:textSize="16sp" />
    </RelativeLayout>

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

</LinearLayout>

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:background="@android:color/black"
    android:padding="5dp" >

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

</RelativeLayout>

MainActivity.java:
package cn.leigo.db;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import cn.leigo.domain.Person;
import cn.leigo.service.PersonService;

public class MainActivity extends Activity {
	private PersonService service;
	private ListView lv;

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

		service = new PersonService(this);
		lv = (ListView) findViewById(R.id.lv);

		show();
	}

	private void show() {
	}

}


1.利用SimpleAdapter繫結資料

private void show() {
		List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		List<Person> persons = service.getScrollData(0, 20);
		for (Person person : persons) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", person.getName());
			map.put("phone", person.getPhone());
			map.put("amount", person.getAmount());
			data.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
				new String[] { "name", "phone", "amount" }, new int[] {
						R.id.tv_name, R.id.tv_phone, R.id.tv_amount });
		lv.setAdapter(adapter);
	}

2.利用SimpleCursorAdapter繫結資料,SimpleCursorAdapter繫結的資料中必須有一個名為"_id"的欄位

private void show2() {
		Cursor c = service.getScrollDataCursor(0, 20);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, c, new String[]{"name", "phone", "amount"}, 
				new int[]{R.id.tv_name, R.id.tv_phone, R.id.tv_amount});
		lv.setAdapter(adapter);
	}

/**
	 * 分頁獲取記錄
	 * 
	 * @param offset跳過前面多少條記錄
	 * @param maxResult每頁獲取多少條記錄
	 * @return
	 */
	public Cursor getScrollDataCursor(int offset, int maxResult) {
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"SELECT personid as _id,name,phone,amount FROM person order by personid asc limit ?,?",
				new String[] { offset + "", maxResult + "" });
		return cursor;
	}

3.利用自定義介面卡繫結資料
// 自定義介面卡
	private void show3() {
		List<Person> persons = service.getScrollData(0, 20);
		PersonAdapter adapter = new PersonAdapter(this, persons);
		lv.setAdapter(adapter);
	}

package cn.leigo.adapter;

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 cn.leigo.db.R;
import cn.leigo.domain.Person;

public class PersonAdapter extends BaseAdapter {
	private List<Person> persons; // 繫結的資料
	private LayoutInflater inflater;

	public PersonAdapter(Context context, List<Person> persons) {
		this.persons = persons;
		inflater = LayoutInflater.from(context);
	}

	@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;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item, null);

			holder = new ViewHolder();
			holder.nameView = (TextView) convertView.findViewById(R.id.tv_name);
			holder.phoneView = (TextView) convertView
					.findViewById(R.id.tv_phone);
			holder.amountView = (TextView) convertView
					.findViewById(R.id.tv_amount);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		Person person = persons.get(position);
		// 實現資料繫結
		holder.nameView.setText(person.getName());
		holder.phoneView.setText(person.getPhone());
		holder.amountView.setText(person.getAmount() + "");
		return convertView;
	}

	static class ViewHolder {
		TextView nameView;
		TextView phoneView;
		TextView amountView;
	}

}

監聽ListView的點選事件:

實現AdapterView.OnItemClickListener介面,重寫onItemClick()方法

@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		//1.SimpleAdapter
		HashMap<String, Object> map = (HashMap<String, Object>)parent.getItemAtPosition(position);
		String name = (String) map.get("name");
		Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
		//2.SimpleCursorAdapter
		//Cursor c = (Cursor)parent.getItemAtPosition(position);
		//String name = c.getString(c.getColumnIndex("name"));
		//Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
		//3自定義介面卡
		//Person person = (Person) parent.getItemAtPosition(position);
		//Toast.makeText(this, person.getName(), Toast.LENGTH_SHORT).show();
	}

parent.getItemAtPosition(position)
得到的型別由public Object getItem(int position) 返回的型別決定。

相關推薦

Android開發入門採用ListView實現資料列表顯示

再次用到上一篇寫過的db工程, activity_main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://s

Android採用ListView實現資料列表顯示

(1)、首先設計介面,使用上面一個數據庫專案,將資料庫中的所有資料用ListView顯示在螢幕上:新建一個佈局檔案item.xml <TextView        android:layou

Android開發入門實現動態註冊廣播監聽網路變化

最近在學習Android開發中廣播的相關內容。 註冊廣播的方式有兩種,在程式碼中註冊和在AndroidManifest.xml中註冊,其中前者也被稱為動態註冊,後者被稱為靜態註冊。以註冊廣播監聽網路變化為例,附上實現動態註冊的步驟: 1、 class Netwo

Android開發學習路--圖表實現(achartengine/MPAndroidChart)初體驗

bundle 喜歡 嵌入式linux Y軸 tid ren sca ref java代碼 ??已經有一段時間沒有更新博客了,在上周離開工作了4年的公司,從此不再安安穩穩地工作了。很多其它的是接受挑戰和實現自身價值的提高。離開了嵌入式linux,從此擁抱移

Android開發入門第一個安卓工程:HelloWorld!

前提: 已安裝完畢AndroidStudio,安裝指導可以參考:https://www.jianshu.com/p/a0e0e11cac1f 開始第一個安卓工程 新建工程 第一步中如果是Kotlin,就勾選“Include Kotlin support”;否則就不勾選

九、androidListView實現資料列表展示

基於上一篇第八節的資料庫操作為基礎,對資料庫中的內容在android介面上進行列表展示 1、工程結構: 列表顯示示意圖: 列表顯示效果圖: 2、介面的列表展示配置檔案 item.xml: <?xml version="1.0" encoding="utf-8"

Android開發學習基於ZBar實現微信掃一掃

          蟄伏半月有餘,一直在準備期末考試,期間抽空研究了一些Android的原始碼,現在我就把在這其中的一些收穫分享給大家。        今天想分享給大家的是二維碼掃描。說起二維碼,大家一定不會陌生,尤其是微信火了以後,在我們的生活中幾乎隨處都可以看到二維碼的

Android四大元件使用ContentProvider實現資料共享

ContendProvider是不同應用程式之間進行資料交換的標準API,ContentProvider以某種Uri的形式對外提供資料,允許其他應用訪問或修改資料;其他應用程式使用ContentReslover根據Uri去訪問操作指定資料 因為ContendP

android——kotlin開發入門開發環境搭建

style blog extension activity image plugins 重要 打開 對話框 一.打開android studio—Setting—Plugins 註意,第一次是搜索不到的,會彈出一個對話框,在對話框中輸入Kotlin,選中第二個。在右邊點擊

AndroidListView實現展示列表資料

1、在activity_main.xml中新增一個ListView <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://sc

Android中的AOP程式設計AspectJ實戰實現資料埋點

文章背景 最近在給某某銀行做專案的時,涉及到了資料埋點,效能監控等問題,那我們起先想到的有兩種方案,方案之一就是藉助第三方,比如友盟、Bugly等,由於專案是部署在銀行的網路框架之內的,所以該方案不可行。另外一種方案是就是給每一個方法裡面資料打點,然後寫入S

Android ListView實現分頁顯示資料

當有大量的資料需要載入到ListView的Adapter中時,全部一次性載入,通常會非常耗時,這將嚴重影響使用者的體驗性和流暢性,而分頁載入則會優化載入的速度,先暫時顯示一頁能夠顯示的資料項,在拖動到最下方時或點選了“顯示更多”按鈕時,再載入部分(需要自己定義每次顯示多少)

Android開發筆記RecycleView載入不同item佈局的實現

RecycleView是安卓5.0版本以後推出的新控制元件 優點 想要控制其顯示的方式,請通過佈局管理器LayoutManager 想要控制Item間的間隔(可繪製),請通過ItemDecoration 想要控制Item增刪的動畫,請通過ItemAnima

Android開發筆記自定義控制元件(物流時間軸的實現)

最近修改專案遇到檢視物流這個需求,經過一個下午的時間的終於搞定,趁著這個時間點,趕快把這個功能抽取出來,方便大家以後開發的需要,幫助到更多的人 先看效果圖,如下 看完之後,分析可知道,主要是兩部分,一個頭部和一個body. 那我們最主要的工作就是bod

Android開發筆記notification訊息推送 通知欄的實現

訊息通知欄的實現我們要通過builder工廠來建立一個notification的物件我們建立一個點選了通知欄訊息要跳轉到的activityIntent intent = new Intent(conte

Android 開發入門Android裝置監視器除錯工具DDMS使用初探

Android Studio提供了一個很實用的工具Android裝置監視器(Android device monitor),該監視器中最常用的一個工具就是DDMS(Dalvik Debug Monitor Service),是 Android 開發環境中的Dalvik虛擬機器

Android開發學習路--資料持久化初體驗

    上班第一天,雖然工作上處於醬油模式,但是學習上依舊不能拉下,接著學習android開發吧,這裡學習資料持久化的 知識。     其實資料持久化就是資料可以儲存起來,一般我們儲存資料都是以檔案,或者資料庫的形式儲存的,android程式也有 檔案和資料庫的儲存,此外還

Android開發學習使用百度語音識別SDK實現語音識別(上)

        作為移動網際網路殺手級的互動方式,語音識別從問世以來就一直備受人們的關注,從IOS的Siri到國內的訊飛語音,語音識別技術在移動開發領域是最為充滿前景和希望的技術。Android作為一個移動作業系統,其本身就繼承了Google天生的搜尋基因,因此Androi

Android開發學習卡片式佈局的簡單實現

             GoogleNow是Android4.1全新推出的一款應用,它可以全面瞭解你的使用習慣,併為你提供現在或者未來可能用到的各種資訊,GoogleNow提供的資訊關聯度較高,幾乎

08、Android開發基礎QQ登陸介面的實現

Android開發基礎之QQ登陸介面的實現 思路分析 這個QQ登陸介面怎麼去實現呢? 也是非常簡單的一件事情! 我們整體一個相對佈局,然後上面部分使用一個線性佈局!我們要考慮一下方向即可,對吧! 直接看效果圖吧! 學習怎麼做的話,大家就看視訊好了