首先说一下在其中遇到的的一个巨大的Bug.
由于没有在意ListView的id的设置导致程序出错。
对初学者来说我的理解是:ListView不像其他控件那样必须进行findviewbyid操作,因为ListView有默认的id那就是android:list
详见下面的代码
xml1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
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="com.example.genius.listview.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/android:list"
<!--就是这里对id 的设置-->
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:drawSelectorOnTop="false">
<!--scrollobars是ListView的数量超过屏幕大小后的填充方式-->
</ListView>
</LinearLayout>
</LinearLayout>
xml2
<?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="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/username"
android:layout_gravity="left"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/phone"
android:layout_gravity="right"/>
</LinearLayout>
MainActivity
package com.example.genius.listview;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
HashMap<String, String> map2 = new HashMap<>();
HashMap<String, String> map3 = new HashMap<>();
map1.put("username", "Tom");
map1.put("phone", "1105221");
map2.put("username", "kite");
map2.put("phone", "555451");
map3.put("username", "Pig");
map3.put("phone", "751521");
list.add(map1);
list.add(map2);
list.add(map3);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.user,
new String[]{"username", "phone"}, new int[]{R.id.username, R.id.phone});
setListAdapter(simpleAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//you can do something you want to do here .
}
}