[Android] ListView 结合SimpleAdapter使用
16lz
2021-01-23
1-声明变量
private ListView listView; private SimpleAdapter simpleAdapter; List<Map<String,Object>> valueList = new ArrayList<>(); Map<String, Object> mapRow0 = new HashMap<>(); Map<String, Object> mapRow1 = new HashMap<>(); Map<String, Object> mapRow2 = new HashMap<>(); Map<String, Object> mapRow3 = new HashMap<>();
2-Map添加映射
mapRow0.put("view0","第1个View"); mapRow0.put("view1","第2个View"); mapRow1.put("view0","第1个View"); mapRow1.put("view1","第2个View"); mapRow2.put("view0","第1个View"); mapRow2.put("view1","第2个View"); mapRow3.put("view0","第1个View"); mapRow3.put("view1","第2个View");
3-将Map添加到List中
valueList.add(mapRow0); valueList.add(mapRow1); valueList.add(mapRow2); valueList.add(mapRow3);
4-给listView,sampleAdapter赋值,关联listView
listView = (ListView) findViewById(R.id.listview); SimpleAdapter = new SimpleAdapter(MainActivity.this, valueList, R.layout.test_layout, new String[]{"view0","view1"}, new int[]{R.id.gg1,R.id.gg2}); listView.setAdapter(SimpleAdapter);
这里的view0与test_layout中的gg1关联,view1与test_layout中的gg2关联;
5-设置Touch事件
listView.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if(event.getAction() == MotionEvent.ACTION_DOWN) { //listView.setBackgroundColor(Color.BLUE); Toast.makeText(MainActivity.this, "TOUCH.....", Toast.LENGTH_LONG).show(); //startActivity(new Intent(MainActivity.this,LoginActivity.class)); mapRow0.put("view0","第1个 Touch-Row0"); mapRow0.put("view1","第2个 Touch-Row0"); listView.setAdapter(simpleAdapter); } return false; } });
修改mapRow0中的值,不用重新设置适配器simpleAdapter,只用让listView重新加载适配器即可。
6-test_layout.xml编写
<?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/testlayout"> <TextView android:text="TextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/gg1" /> <TextView android:text="TextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/gg2" />LinearLayout>
更多相关文章
- Android之Audio常用属性变量
- Android Ant打包及其环境变量配置
- DataBinding赋值本地图片src
- android入门知识:android使用全局变量
- Mac修改环境变量路径中带空格的处理
- Android SDK环境变量配置(windows和Linux)
- Android之BaseAdapter适配器使用技巧
- Android 如何配置adb环境变量