今天看了隋雨辰老师讲的 ListView,按照例子内容没有出现预期的效果,于是查资料看了一下,发现是list_item.xml写错了,以下为源代码:
Java代码:
package com.example.mylistview2;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView) findViewById(R.id.listView1);
ArrayList<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
for(int i=0;i<mStrArr.length;i++){
HashMap<String,String> map=new HashMap<String,String>();
map.put("title","title"+i);
map.put("subtitle",mStrArr[i]);
data.add(map);
}
String[] from=new String[]{"title","subtitle"};
int[] to=new int[]{R.id.tv_title,R.id.tv_subtitle};
listView.setAdapter(new SimpleAdapter(this,data,R.layout.list_item,from,to));
}
private String[] mStrArr=new String[]{"aaa","bbb","ccc","ddd","eee"};
@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;
}
}
list_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="vertical" >
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/ >
<TextView
android:id="@+id/tv_subtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</LinearLayout>
main.xml:
<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:gravity="top"
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>