转载请注明出处:ListView、Map、SimpleAdapter组合_Mr_Leixiansheng的博客-CSDN博客
注意:布局时应分清控件优先级、焦点需要汇集在ListView上
(此处CheckBox的点击事件优先级比ListView高,所以需要屏蔽,否则点击无响应)(博主就是在这儿卡了半天)
步骤:
(基本和普通listview操作一样)
1、主布局添加好ListView控件
2、添加ListView需要显示的布局样式xlm文件
3、实例化包含map的数组,加入要显示的内容
4、配置SimpleAdapter
5、ListView添加设置好的适配器
6、设置ListView的监听
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/RelativeLayout01">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/content"
android:text="Text"
android:textSize="20dp"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/image"
android:layout_toRightOf="@+id/content"
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="@+id/c_box"
android:focusable="false"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
package com.example.leixiansheng.listview1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("DATA", "data " + (i + 1));
map.put("PIC", R.mipmap.ic_launcher);
arrayList.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, arrayList, R.layout.arts_layout,
new String[]{"DATA", "PIC"}, new int[]{R.id.content, R.id.image});
listView = (ListView) findViewById(R.id.list_item);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String str = arrayList.get(i).get("DATA").toString();
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
}