Android-Adapter實現方法(ArrayAdapter,SimpleAdapter,SimpleCursorAdapter)

Adapter

總結

Adapter常用的實現類包括ArrayAdapter、SimpleAdapter、SimpleCursorAdapter、BaseAdapter。Adapter可以實現數據先加載再動態顯示在界面上,而不是固定死界面有多少個列表(類似於web開發中的動態網頁),是一個非常重要的內容。

Adapter 常用實現類:

類型 描述
ArrayAdapter 將數組或List集合的多個值包裝成多個列表項
SimpleAdapter 將List集合的多個對象包裝成多個列表項
SimpleCursorAdapter 包裝Cursor提供的數據
BaseAdapter 可對各列表項進行最大限度地定製

ArrayAdapter(基於ListActivity)

使用簡單,但是隻能實現文本內容(TextView)

package com.example.huaro.proj_09;

import android.app.ListActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] arr=new String[]{
                "豬八戒",
                "何洪達",
                "萌萌噠"
        };
        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,arr);
        setListAdapter(arrayAdapter);
    }
}

SimpleAdapter (圖片和文字)

並不簡單,功能強大,大部分的列表實現均可使用SimpleAdapter

<!--main界面代碼,定義一個ListView-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>
<!--simple_item界面代碼 嵌入main界面中的ListView-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<ImageView
    android:id="@+id/header"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/name"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:id="@+id/desc"/>
    </LinearLayout>
</LinearLayout>
//Activity代碼
package com.example.huaro.proj_09;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

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

/**
 * Created by HUARO on 2016/2/10 0010.
 */
public class Test extends Activity{
    //位於/res/drawable下的三張圖片
    private int[] images=new int[]{
            R.drawable.img_08,
            R.drawable.img_08,
            R.drawable.img_08
    };
    //數據
    private String[] names=new String[]{
            "你好",
            "萌萌噠",
            "呵呵大"
    };
    //數據
    private String[] descs=new String[]{
            "我就是我不一樣的煙火",
            "你就是你",
            "哈哈"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加載界面
        setContentView(R.layout.main);
        //定義List集合
        List<Map<String,Object>> listmap=new ArrayList<Map<String,Object>>();
        //List集合添加數據
        for (int i=0;i<names.length;i++){
            Map<String,Object> listItem=new HashMap<String,Object>();
            listItem.put("header",images[i]);
            listItem.put("personName",names[i]);
            listItem.put("desc",descs[i]);
            listmap.add(listItem);
        }

        /*
         *創建一個simpleListView
         *參數(context,List,view,String[]{"list中的各項參數"},int[]{"對應顯示界面的id"})
        */
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,listmap,R.layout.simple_item,new String[]{"personName","header","desc"},new int[]{R.id.name,R.id.header,R.id.desc});
        //獲取界面ListView
        ListView list=(ListView)findViewById(R.id.mylist);
        //爲ListView設置Adapter
        list.setAdapter(simpleAdapter);
        //爲ListView的列表項綁定點擊事件
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //Toast提示消息
            Toast.makeText(MainActivity.this, "數據"+names[position]+":"+descs[position], Toast.LENGTH_SHORT).show();
            }
        });
        list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //Toast提示消息
            Toast.makeText(MainActivity.this, "數據"+names[position]+":"+descs[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

SimpleAdapter實例

SimpleCursorAdapter(SQLite數據庫)

<!--兩個文本框,一個按鈕,用作數據插入數據庫-->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.huaro.proj_data_sqlite.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/edit1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/edit2"
        android:layout_below="@+id/edit1"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="插入"
        android:id="@+id/button"
        android:layout_below="@+id/edit2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:onClick="insertSQL"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
<!--用作顯示數據庫內容-->
<?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:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/my_title"
        android:layout_weight="0.03" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/my_content"
        android:layout_weight="0.06" />
</LinearLayout>
package com.example.huaro.proj_data_sqlite;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends AppCompatActivity {

    SQLiteDatabase sqLiteDatabase;
    ListView listView;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sqLiteDatabase=SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"my.db3",null);
        listView=(ListView)findViewById(R.id.show);
    }
    public void insertSQL(View view){
        String title=((EditText)findViewById(R.id.edit1)).getText().toString();
        String content=((EditText)findViewById(R.id.edit2)).getText().toString();
        try{
            insertData(sqLiteDatabase,title,content);
            Cursor cursor=sqLiteDatabase.rawQuery("select *from news_inf",null);
            inflateList(cursor);
        }catch (Exception e){
            //執行ddl創建數據表
            sqLiteDatabase.execSQL("create table news_inf(_id integer"+" primary key autoincrement,"+" news_title varchar(50),"+" news_content varchar(255))");
            //執行insert語句插入數據
            insertData(sqLiteDatabase,title,content);
            //執行查詢
            Cursor cursor=sqLiteDatabase.rawQuery("select *from news_inf",null);
            inflateList(cursor);
        }

    }
    private void insertData(SQLiteDatabase db,String title,String content){
        //執行插入語句
        db.execSQL("insert into news_inf values(null,?,?)",new String[]{title,content});
    }
    private void inflateList(Cursor cursor){
        //填充SimpleCursorAdapter
        SimpleCursorAdapter simpleCursorAdapter=new SimpleCursorAdapter(MainActivity.this,R.layout.line,cursor,new String[]{"news_title","news_content"},new int[]{R.id.my_title,R.id.my_content}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        //顯示數據
        listView.setAdapter(simpleCursorAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出程序時關閉SQLiteDatabase
        if(sqLiteDatabase!=null&&sqLiteDatabase.isOpen()){
            sqLiteDatabase.close();
        }
    }
}

SimpleCustorAdapter實例

do a small fish in the sea;

發佈了37 篇原創文章 · 獲贊 63 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章