安卓適配器——SimpleAdapter

SimpleAdapter:佈局方式爲兩個字符串

所以需要指定哪個字符串對應哪個組件

package net.onest.simpleadapterch0203;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //準備數據源
        //這裏map中放入幾組就是幾個列表元素
        List<Map<String, String>> students = new ArrayList<>();
        Map<String, String> stu1 = new HashMap<>();
        stu1.put("name", "張三");
        stu1.put("stuNo", "2018011785");
        Map<String, String> stu2 = new HashMap<>();
        stu2.put("name","李四");
        stu2.put("stuNo","2018011786");
        students.add(stu1);
        students.add(stu2);
        //準備item佈局文件(自帶的佈局文件)
        //創建Adapter,綁定Adapter
        //這裏數據源和佈局文件準備好後,要將數據源的屬性(鍵)和組件id對應起來
        SimpleAdapter myAdapter = new SimpleAdapter(this,//環境上下文
                students,//數據源
                android.R.layout.simple_list_item_2,//item的佈局文件
                new String[]{"name","stuNo"},//數據源中Map的key值
                new int[]{android.R.id.text1, android.R.id.text2});//item佈局當中顯示內容的控件的id

        ListView studentListView = findViewById(R.id.lv_student);
        studentListView.setAdapter(myAdapter);
        //設置ListView的監聽器
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章