Android学习笔记之ListView的简单使用

(1)

<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="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

(2)

package com.example.listview1;

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

import android.R.anim;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private ListView listView1;
	private ArrayAdapter<String> arrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView1 = (ListView) this.findViewById(R.id.listView1);

		// 设置可选项、还可以设置为单选CHOICE_MODE_SINGLE、下边的simple也应该对应
		listView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);// 设置listView1的选中模式,与下边的simple_list_item_multiple_choice对应
		arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
				android.R.layout.simple_list_item_multiple_choice,
				getDataSource());
		listView1.setAdapter(arrayAdapter);
		/*
		 * listView1的点击事件
		 */
		listView1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this,
						"-->>" + arrayAdapter.getItem(position),
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public List<String> getDataSource() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 30; i++) {
			list.add("jack" + i);
		}
		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Android学习笔记之ListView的简单使用_第1张图片

你可能感兴趣的:(ListView,Adapter)