Android之ListView與SimpleAdapter的使用

君墨痕發表於2013-10-30

先說明一下,這裡的資料使用sqlite裡面存進去的,後面會寫sqlite的具體使用

直接看效果圖



首先在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/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2" >
    </ListView>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/add" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="@string/queryAll" />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:text="@string/update" />

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/update"
        android:layout_alignBottom="@+id/update"
        android:layout_alignRight="@+id/listView1"
        android:text="@string/delete" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button2"
        android:text="@string/interf" />

    <Button
        android:id="@+id/add2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button3"
        android:layout_alignBottom="@+id/button3"
        android:layout_alignParentRight="true"
        android:text="@string/add2" />

</RelativeLayout>

然後為每一行記錄定義一個佈局my_listvie.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    android:paddingLeft="12dip"
    android:paddingRight="12dip" >

    <ImageView
        android:id="@+id/ItemImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:contentDescription="@string/hello"
        android:paddingTop="12dip" />

    <TextView
        android:id="@+id/ItemTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/textview01"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/ItemText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ItemTitle"
        android:text="@string/textview02" />

</RelativeLayout>

然後是程式執行的MainActivity類,裡面有些介面呼叫的可以忽略不看,直接看display()方法就可以,

public class MainActivity extends Activity implements OnClickListener {

	private ListView lv;
	private Button btn1;
	private Button btn2;
	private Button interf;
	private Button add;
	private Button delete;
	private Button update;
	private DBManager mgr;

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

		mgr = new DBManager(this);

		btn1 = (Button) findViewById(R.id.button1);
		btn2 = (Button) findViewById(R.id.button2);
		interf = (Button) findViewById(R.id.button3);

		add = (Button) findViewById(R.id.add2);
		delete = (Button) findViewById(R.id.delete);
		update = (Button) findViewById(R.id.update);

		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		interf.setOnClickListener(this);
		add.setOnClickListener(this);
		delete.setOnClickListener(this);
		update.setOnClickListener(this);
	}

	public void add() {
		for (int i = 1; i <= 5; i++) {
			Person person = new Person("yang-" + i, 23, "Hello world-" + i);
			mgr.add(person);
		}
	}

	public void queryAll() {
		List<Person> persons = mgr.queryAll();
		display(persons);
	}

	public void interfaceInvocation() {
		ContentResolver resolver = this.getContentResolver();
		Uri uri = Uri.parse("content://com.example.z_sqlite.yang/query");
		Cursor cursor = resolver.query(uri, null, null, null, null);
		List<Person> persons = new ArrayList<Person>();
		if (cursor.moveToFirst()) {
			while (!cursor.isAfterLast()) {
				Person person = new Person();
				person.setId(cursor.getInt(cursor.getColumnIndex("id")));
				person.setName(cursor.getString(cursor.getColumnIndex("name")));
				person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
				person.setInfo(cursor.getString(cursor.getColumnIndex("info")));
				persons.add(person);
				cursor.moveToNext();
			}
			cursor.close();
		}
		display(persons);
	}

	public void display(List<Person> persons) {
		lv = (ListView) findViewById(R.id.listView1);

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		for (Person person : persons) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", R.drawable.favicon);
			map.put("name", person.getName());
			map.put("ageinfo",
					"id:" + person.getId() + ",今年 " + person.getAge()
							+ " 歲,個人資訊:" + person.getInfo());
			list.add(map);
		}

		// 介面卡
		SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.my_listvie,
				new String[] { "ItemImage", "name", "ageinfo" }, new int[] {
						R.id.ItemImage, R.id.ItemTitle, R.id.ItemText });

		// 顯示
		lv.setAdapter(sa);

		// 為每個Item新增監聽
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "點選了第" + position + "個Item:",
						Toast.LENGTH_SHORT).show();
			}
		});

		// 新增長按點選
		lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {

				menu.setHeaderTitle("長按選單-ContextMenu");
				menu.add(0, 1, 1, "修改");
				menu.add(0, 2, 2, "刪除");
				menu.add(1, 3, 3, "更多");
			}
		});
	}

	// 長按選單響應函式
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		setTitle("點選了長按選單裡面的第" + item.getItemId() + "個專案");
		return super.onContextItemSelected(item);
	}

	public void add2() {
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://com.example.z_sqlite.yang/insert");
		ContentValues cv = new ContentValues();
		cv.put("name", "willwind");
		cv.put("age", 120);
		cv.put("info", "到此一遊,好睏阿!");
		Uri temp = resolver.insert(uri, cv);
		Log.i("介面呼叫", "delete ---" + temp);
	}

	public void delete() {
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://com.example.z_sqlite.yang/delete");
		int flag = resolver.delete(uri, "id=?", new String[] { "10" });
		Log.i("介面呼叫", "delete ---" + flag);
	}

	public void update() {
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://com.example.z_sqlite.yang/update");
		ContentValues cv = new ContentValues();
		cv.put("name", "yangxuan");
		cv.put("age", 120);
		int flag = resolver.update(uri, cv, "id=?", new String[] { "11" });
		Log.i("介面呼叫", "update ---" + flag);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btn1) {
			add();
			Toast.makeText(MainActivity.this, "資料新增成功!", Toast.LENGTH_SHORT)
					.show();
			Uri uri = Uri.parse("content://aaa.bbb.ccc");
			v.getContext().getContentResolver().notifyChange(uri, null);
		} else if (v == btn2) {
			queryAll();
			Toast.makeText(MainActivity.this, "查詢成功!", Toast.LENGTH_SHORT)
					.show();
		} else if (v == interf) {
			interfaceInvocation();
			Toast.makeText(MainActivity.this, "介面呼叫查詢成功!", Toast.LENGTH_SHORT)
					.show();
		} else if (v == add) {
			add2();
			Toast.makeText(MainActivity.this, "介面呼叫新增成功!", Toast.LENGTH_SHORT)
					.show();
		} else if (v == delete) {
			delete();
			Toast.makeText(MainActivity.this, "介面呼叫刪除成功!", Toast.LENGTH_SHORT)
					.show();
		} else if (v == update) {
			update();
			Toast.makeText(MainActivity.this, "介面呼叫修改成功!", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mgr.closeDB();
		super.onDestroy();
	}
}


相關文章