第十二章 Android常用的ListView (二)

上一章講了ListView的屬性,用法,優化,這一章繼續補上SimpleAdapter和SimpleCursorAdapter。

1. SimpleAdapter

1.1SimpleAdapter的構造方法

要了解SimpleAdapter, 就必須了解 它的構造方法 :
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
1.Context context:上下文,這個是每個組件都需要的,它指明了SimpleAdapter關聯的View的運行環境,也就是我們當前的Activity。
2.List<? extends Map<String, ?>> data:這是一個由Map組成的List,在該List中的每個條目對應ListView的一行,每一個Map中包含的就是所有在from參數中指定的key。
3.int resource:定義列表項的布局文件的資源ID,該資源文件至少應該包含在to參數中定義的ID。
4.String[] from:將被添加到Map映射上的key。
5.int[] to:將綁定數據的視圖的ID跟from參數對應。

1.2.SimpleAdapterde 的使用方法:

在了解了SimpleAdapter的構造方法之后,只需要滿足SimpleAdapter的構造方法里面的參數

public class MainActivity extends AppCompatActivity {

    private String[] items = new String[]{"擦汗", "豬頭", "玫瑰"};
    private int[] imgs = new int[]{R.mipmap.f006, R.mipmap.f007, R.mipmap.f008};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView= (ListView) findViewById(R.id.lv_list);
        // 簡易適配器
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, getData(), R.layout.layout_item, new String[]{"txt", "img"}, new int[]{R.id.tv, R.id.iv});
        listView.setAdapter(simpleAdapter);
    }

//將數據通過for循環放在map里面,然后將map撞到List中
![image.png](http://upload-images.jianshu.io/upload_images/1869441-bfd141acf43509c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        for (int i = 0; i < items.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("txt", items[i]);
            map.put("img", imgs[i]);
            list.add(map);
        }
        return list;
    }
}


簡易適配器

github地址:https://github.com/wangxin3119/github

2. SimpleCursorAdapter

在使用SQLite進行數據的操作的時候,Cursor這個游標應該不會陌生吧,在連接數據庫和視圖的時候,Android 提供了SimpleCursorAdapter這個適配器。

2.1 SimpleCursorAdapter的使用

1.執行數據庫的增刪查改操作,返回一個Cursor操作,將這個cursor放入SimpleCursorAdapter的構造函數。
2.setadapter 即可

效果圖:

simplecursoradapter的使用

1.創建一個工具類DBUtil.java,創建數據庫,建表,進行數據庫的增刪查改操作。

ublic class DBUtils {
    
    private final SQLiteDatabase db;
    private String sql;
    private  Cursor c;
    private String name;
    private String salary;

    //創建或打開數據

    /**
     * 參數說明:
     * 1.創建或者打開數據庫
     * 2.設置創建或打開數據庫的模式為私有
     * 3.cursorfactory 工廠模式通常設置為null就夠了
     */

    public DBUtils(Context context) {
        db = context.openOrCreateDatabase("android.db", context.MODE_PRIVATE, null);
       createTablePerson();
    }

    //創建Person表
    private void createTablePerson() {
        sql = "CREATE TABLE IF NOT EXISTS PERSON (id integer PRIMARY KEY AUTOINCREMENT ,name VARCHAR2(20) ,salary VARCHAR2(20))";
        db.execSQL(sql);
    }

    //數據庫的操作
    //查詢
    //1.查詢語句
    //2.參數1:要執行的SQL語句
    //   參數2:SQL語句中對應的?的值
    public Cursor  query(){
        sql="SELECT id  _id,name,salary FROM person";
        c=db.rawQuery(sql,null);
        return  c;
    }

    //查詢所有的人的信息

    public  Cursor  query2(){
       c=db.query("person" ,
               new String[]{"id,_id","name","salary"},
               null,
               null,//查詢條件中所對應的值
               null,//分組
               null,//分組條件
               null//排序
               );
        return  c;
    }

    //保存數據
    //方法一:
    public  void insert1(String name,String salary){
        sql="INSERT INTO person(name,salary) VALUES(?,?)";
        db.execSQL(sql,new Object[]{name,salary});
    }
    //保存數據
    //方法二:
    public  void  insert2(String name,String salary){
        ContentValues values=new ContentValues();
        values.put("name",name);
        values.put("salary",salary);
        db.insert("person",null,values);
    }

    //刪除數據  方法一:
    public  void   delete(String  id){
        sql="DELETE FROM person WHERE id=?";
        db.execSQL(sql,new String[]{id});
    }
    //刪除數據 方法二:
    public  void  delete2(String id){
        db.delete("person","id=?",new String[]{id});
    }

    //修改數據方法一:
    public void update(String salary,String id){
        sql="UPDATE person SET salary=? WHERE id=?";
        db.execSQL(sql,new String[] {salary,id});
    }
    //修改數據方法二:
    public void update2(String id,String salary){
        ContentValues values=new ContentValues();
        values.put("salary",salary);
        db.update("person",values,"id=?",new String[]{id});
    }
}


2.自定義適配器,


public class MySimpleCursorDapater  extends SimpleCursorAdapter {

    private Button  btn01,btn02;
    private String  sql;
    private  DBUtils db;
    private  Cursor c;

    //構造方法,選擇第二種,第一種已經廢棄了
    /**
     *
     * @param context 上下文
     * @param layout 布局
     * @param c       游標對象
     * @param from   字符串數組
     * @param to    int數組 上面字段需要展示對應的控件的id
     * @param flags  標志
     */
    public MySimpleCursorDapater(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
        this.c=c;
        db=new DBUtils(context);
    }

    //和BaseAdapter 中的getView的方法類似,都是在展示每一個item的時候被調用
    @Override
    public void bindView(final View view, final Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        btn01= (Button) view.findViewById(R.id.button1);
        btn02= (Button) view.findViewById(R.id.button2);
        final TextView tv1=(TextView) view.findViewById(R.id.textView1);
        TextView tv2=(TextView) view.findViewById(R.id.textView2);
        final String id=tv1.getText().toString();
        final String name=tv2.getText().toString();
        //給刪除按鈕添加點擊的監聽事件

        btn02.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                TextView tv=(TextView) view.findViewById(R.id.textView1);
                String id=tv.getText().toString();
                Log.i("tag", "被點擊的數據的id是:"+tv.getText());
                db.delete(id);
                //更新Cursor
                c=db.query();
                //新的Cursor對象替換舊的Cursor對象達到刷新的功能
                MySimpleCursorDapater.this.swapCursor(c);
            }
        });
        btn01.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //彈出自定的對話框
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                //添加對話框的標題
                builder.setTitle("修改工資金額");
                //獲取自定義布局對應的View對象
                View view=LayoutInflater.from(context).inflate(R.layout.custom_dialog_layout, null);
                TextView tv=(TextView) view.findViewById(R.id.textView1);
                final EditText et=(EditText) view.findViewById(R.id.editText1);
                tv.setText(name);
                //對話框加載自定義布局
                builder.setView(view);
                builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    /**
                     * 將修改的內容更新到數據庫中
                     * 獲取需要修改的數據
                     * 同步更新ListView中的數據
                     */
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //更新金額  首先獲取金額
                        String salary=et.getText().toString();
                        db.update(salary, id);
                        c=db.query();
                        MySimpleCursorDapater.this.swapCursor(c);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }

                });
                builder.show();
            }
        });

    }
}

3.最后在Activity中,調用DBUtils和MySimpleCursorAdapter


public class MainActivity extends AppCompatActivity {

    public EditText  edit01,edit02;
    private ListView listView;
    private DBUtils dbUtils;
    private Cursor cursor;
    MySimpleCursorDapater adapter;
    private String salary;
    private String name;

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

    private void initView() {
        edit01= (EditText) findViewById(R.id.id_et1);
        edit02= (EditText) findViewById(R.id.id_et2);
        listView= (ListView) findViewById(R.id.id_listview);
        dbUtils=new DBUtils(this);
        //查詢出所有的人信息獲取Cursor對象
        cursor = dbUtils.query();
        String from []={"_id","name","salary"};
        int to[]={R.id.textView1,R.id.textView2,R.id.textView3};
        adapter=new MySimpleCursorDapater(this,
                R.layout.custom_item_layout,
                cursor,
                from,
                to,
                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listView.setAdapter(adapter);
    }

    public  void  commitData(View v){
        name=edit01.getText().toString();
        salary=edit02.getText().toString();
        //將數據寫入person表中
        dbUtils.insert1(name,salary);
        //重新查詢數據更新Cursor對象
        cursor=dbUtils.query();
        //刷新
        adapter.swapCursor(cursor);
    }



}

github地址:https://github.com/wangxin3119/simpeCursorAdapter

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容