[Android] ListView 结合SimpleAdapter使用

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编写


<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)