这几天关于这个ListView一团乱。现在重新梳理下:
①项vlist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/materialName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30px" />
<TextView android:id="@+id/materialFormat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px" />
<TextView android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px" />
</LinearLayout>
②页面activity_list.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" >
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ListView01"
/>
</LinearLayout>
③ListViewActivity.xml:
package cn.com.smartcost.offer.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.com.smartcost.offer.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//绑定Layout里面的ListView
ListView list = (ListView) findViewById(R.id.ListView01);
//生成动态数组,加入数据
List<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
for(int i=0;i<10;i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("materialName", "Level "+i);
map.put("materialFormat", "Finished in 1 Min 54 Secs, 70 Moves! ");
listItem.add(map);
}
//生成适配器的Item和动态数组对应的元素
SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源
R.layout.vlist,//ListItem的XML实现
//动态数组与ImageItem对应的子项
new String[] {"materialName", "materialFormat"},
new int[] {R.id.materialName,R.id.materialFormat}
);
//添加并且显示
list.setAdapter(listItemAdapter);
//添加点击
list.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListView lView = (ListView)parent;
Map<String, Object> map = (Map<String, Object>) lView.getItemAtPosition(position);
setTitle("点击第"+map.get("materialName").toString()+"个项目");
}
});
}
//长按菜单响应函数
@Override
public boolean onContextItemSelected(MenuItem item) {
setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目");
return super.onContextItemSelected(item);
}
}