Android学习 —— 多种适配器方式实现ListView
筆記摘要:
? ? ? ? ? 本文主要對ListView列表顯示的實現進行了分析,對于列表顯示,分為兩個部分,第一個部分是整體布局,也就是ListView所在的布局,但ListView中的一個個橫條Item布局也需要我們自己去構建,所以需要創建一個Item的布局文件,然后通過配置器來引入,當然也引入一些數據,最后為ListView設置適配器即可。適配器有多種,這里就介紹了幾種不同的適配器:ArrayAdapter、SimpleAdapter、CursorAdapter、以及自定義的Adapter。
ArrayAdapter
ArrayAdapter的使用比較簡單,只需為ListView設置ArrayAdapter,然后傳入要顯示的內容即可。由名字也可以看出,是一個類似于數組的形式,所以條目都統一了樣式,
比較單一,傳值也比較簡便。
main.xml
<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"tools:context=".MainActivity" ><ListViewandroid:id="@+id/lv"android:layout_width="match_parent"android:layout_height="match_parent" /></RelativeLayout>條目顯示布局:listview_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:gravity="center_vertical"android:layout_height="wrap_content"android:orientation="horizontal" ><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/btn_rating_star_on_normal_holo_light" /><TextViewandroid:id="@+id/tv_content"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="我是文本"android:textSize="24sp" /></LinearLayout>
import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleAdapter;public class MainActivity extends Activity {ListView lv; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);lv = (ListView) findViewById(R.id.listView_id);lv.setAdapter(new ArrayAdapter(this,R.layout.listview_item, R.id.tv_content,new String[]{"功能1","功能2","功能3"}));} }
SimpleAdatper
構造函數:
? ? ? ? ? ? SimpleAdapter(Context?context,?List<??extends?Map<String,??>>?data,?int?resource,?String[]?from,?int[]?to)
由SimpleAdapter的構造函數列表可以看出,
? ? ? ? ? ?List<??extends?Map<String,??>>需要一個存儲Map集合的List集合,來提供數據
? ? ? ? ? ? int?resource:一個布局文件來提供頁面布局
? ? ? ? ? ?From:A?list?of?column?names?that?will?be?added?to?the?Map?associated?with?each?item.,需要適配數據的列名,其與Map集合的鍵相對應。
? ? ? ? ? ?To?:?The?views?that?should?display?column?in?the?"from"?parameter.?These?should?all?be?TextViews. 與From相對應的TextView的資源ID
整體布局文件Main.xml
<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"tools:context=".MainActivity" ><TextViewandroid:id="@+id/info_textView" android:text="產品詳細信息"android:textSize="25sp"android:gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"/><ListViewandroid:layout_below="@id/info_textView"android:id="@+id/listView_id" android:layout_width="match_parent"android:layout_height="match_parent"></ListView> </RelativeLayout>條目的布局文件listView_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextViewandroid:id="@+id/model_textView" android:text="型號"android:textSize="20sp"android:gravity="center_horizontal"android:layout_weight="1"android:layout_width="match_parent"android:layout_height="match_parent"/><TextView android:text="顏色"android:textSize="20sp"android:gravity="center_horizontal"android:layout_weight="1"android:id="@+id/color_textView" android:layout_width="match_parent"android:layout_height="match_parent"/><TextView android:text="大小"android:textSize="20sp"android:layout_weight="1"android:gravity="center_horizontal"android:id="@+id/size_textView" android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout>import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.widget.ListView; import android.widget.SimpleAdapter;public class MainActivity extends Activity {private ListView listView;private List<Map<String,String>> data ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listView_id);Map<String,String> itemdata1 = new HashMap<String,String>();itemdata1.put("型號","復古");itemdata1.put("顏色","淺灰");itemdata1.put("大小","Large");Map<String,String> itemdata2 = new HashMap<String,String>();itemdata2.put("型號","時尚");itemdata2.put("顏色","紫金");itemdata2.put("大小","small");data = new ArrayList<Map<String,String>>();data.add(itemdata1);data.add(itemdata2);//SimpleAdapter(Context context, List<? extends Map<String,?>> data, int resource, String[] from, int[] to)//context,上下文 //List<? extends Map<String, ?>> data,提供要顯示的數據//int resource,一個布局文件來提供頁面布局//String[] from, 需要適配數據的列名,其與Map集合的鍵相對應。//int[] to 與from相對應的顯示視圖,必須都是TextView,通過R.id.TextView來引入listView.setAdapter(new SimpleAdapter(this, data, R.layout.listview_item, new String[]{"顏色","型號","大小"}, new int[]{R.id.model_textView,R.id.color_textView,R.id.size_textView}));}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}
CursorAdapter
注意:
? ? 在使用CursorAdapter為Listview適配的時候,Sqlite標準要求cursor必須有一個屬性 "_id",否則就無法使用
? ? 在使用SimpleCursorAdapter時,有一個相同的方法已經過時,對于這樣的處理,為了向下兼容,我們可以將低版本和高版本的方法都提供出 ? ? 去,只需對用戶的版本進行判斷調用響應的方法即可
總體布局文件
<LinearLayoutxmlns: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:orientation="vertical"><LinearLayout android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:text="姓名"android:textSize="23sp"android:id="@+id/name_textView"android:layout_weight="1"android:layout_gravity="center_horizontal"android:gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:text="電話"android:textSize="23sp"android:id="@+id/phone_textView"android:layout_weight="1"android:gravity="center"android:layout_gravity="center_horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:text="收入"android:textSize="23sp"android:id="@+id/money_textView"android:layout_weight="1"android:gravity="center"android:layout_gravity="center_horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout><ListView android:id="@+id/listView_id"android:layout_width="match_parent"android:layout_height="match_parent"></ListView></LinearLayout>
條目布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextViewandroid:text="姓名"android:id="@+id/name_textView"android:textSize="20sp"android:layout_weight="1"android:layout_gravity="center_horizontal"android:gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:text="電話"android:id="@+id/phone_textView"android:textSize="20sp"android:layout_weight="1"android:gravity="center"android:layout_gravity="center_horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:text="收入"android:id="@+id/money_textView"android:textSize="20sp"android:layout_weight="1"android:gravity="center"android:layout_gravity="center_horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"/> </LinearLayout>
MainActivity
import android.app.Activity; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.webkit.WebChromeClient.CustomViewCallback; import android.widget.LinearLayout; import android.widget.ListView;import com.itheima.db.dao.PersonDao2;public class MainActivity extends Activity {private static final String TAG = "MainActivity";private ListView listView;@SuppressWarnings("deprecation")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listView_id);/*PersonDBOpenHelper helper = new PersonDBOpenHelper(this);helper.getWritableDatabase();*/PersonDao dao = new PersonDao(this);Cursor cursor = dao.findAllCursor();//查詢所有的記錄并返回Cursorwhile(cursor.moveToNext()){int id = cursor.getInt(cursor.getColumnIndex("_id"));String name = cursor.getString(cursor.getColumnIndex("name"));String phone = cursor.getString(cursor.getColumnIndex("phone"));int money = cursor.getInt(cursor.getColumnIndex("money"));Log.i(TAG,id+" name: "+name+" phone: "+phone+" money: "+money);}//(Context context, int layout, Cursor c, String[] from, int[] to)if (Build.VERSION.SDK_INT >= 11) {// api 11以上才可以運行listView.setAdapter(new SimpleCursorAdapter(this, R.layout.list_item, cursor,new String[] { "name", "phone", "money" }, new int[] {R.id.name_textView, R.id.phone_textView, R.id.money_textView }, 0));Log.i(TAG,"我是高版本api");} else {// api 11 以下運行listView.setAdapter(new SimpleCursorAdapter(this, R.layout.list_item, cursor,new String[] { "name", "phone", "money" }, new int[] {R.id.name_textView, R.id.phone_textView, R.id.money_textView }));Log.i(TAG,"我是低版本api");}} }自定義Adapter:繼承BaseAdapter
整體布局文件:Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:orientation="vertical"android:layout_height="match_parent"tools:context=".MainActivity" ><LinearLayout android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:text="ID" android:layout_weight="1"android:textSize="18sp"android:gravity="center_horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:text="姓名" android:layout_weight="1"android:textSize="18sp"android:gravity="center_horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:text="電話" android:layout_weight="1"android:textSize="18sp"android:gravity="center_horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:text="收入" android:textSize="18sp"android:layout_weight="1"android:gravity="center_horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout><ListViewandroid:id="@+id/lv"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>Item布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextViewandroid:id="@+id/id_TextView"android:text="ID" android:gravity="center_horizontal"android:layout_width="0dip"android:layout_height="match_parent"android:layout_weight="1"android:textSize="16sp"/><TextViewandroid:id="@+id/name_TextView" android:text="姓名"android:layout_weight="1"android:gravity="center_horizontal"android:layout_width="0dip"android:layout_height="match_parent"android:textSize="16sp"/><TextViewandroid:id="@+id/phone_TextView" android:text="電話"android:layout_weight="1"android:gravity="center_horizontal"android:layout_width="0dip"android:layout_height="match_parent"android:textSize="16sp"/><TextViewandroid:id="@+id/amount_TextView" android:text="收入"android:layout_weight="1"android:gravity="center_horizontal"android:layout_width="0dip"android:layout_height="match_parent"android:textSize="16sp"/> </LinearLayout>MainActivity
public class MainActivity extends Activity {private static final String TAG = "MainActivity";private List<Person> persons ;private PersonDao dao;private ListView lv ;ListAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);lv = (ListView) findViewById(R.id.lv);dao = new PersonDao(this);persons = dao.findAll();adapter = new ListAdapter();Log.i(TAG,adapter.getCount()+"");lv.setAdapter(adapter);//為ListView 設置適配器,適配器中已經將數據填充到了布局中//為ListView設置點擊事件lv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {Person person = persons.get(position);String name = person.getName();int personid = person.getId();//Toast.makeText(MainActivity.this, personid, 1).show();Toast.makeText(MainActivity.this, "id:"+personid, 1).show();}});//為ListView設置長按監聽:刪除一條數據lv.setOnItemLongClickListener(new OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {Person person = persons.get(position);int personid = person.getId();dao.delete(personid);//從數據庫中將數據刪除persons.remove(position);//從適配器中刪除adapter.notifyDataSetChanged();//通知數據適配器 更新界面return true;//false 當前的事件 不會被消費掉,繼續執行,OnItemClickListener會Toaster//true 當前事件執行到這里 就終止了,后面的不再執行,//比如setOnItemClickListener的Toaster就不執行}});}
private final class ListAdapter extends BaseAdapter{@Overridepublic int getCount() {return persons.size();}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}//返回當前位置對應的view對象,顯示內容@Overridepublic View getView(int position, View convertView, ViewGroup parent) {//position代表位置//通過View關聯自定義Item布局,進行填充View view = View.inflate(MainActivity.this, R.layout.list_item, null);//獲取指定位置的對象Person person = persons.get(position);//獲取要顯示的組件,注意findViewById的調用對象是上面填充了Item的布局的對象ViewTextView id_TextView = (TextView)view.findViewById(R.id.id_TextView);TextView name_TextView = (TextView)view.findViewById(R.id.name_TextView);TextView amount_TextView =(TextView)view.findViewById(R.id.amount_TextView);TextView phone_TextView =(TextView)view.findViewById(R.id.phone_TextView);id_TextView.setText(person.getId()+"");name_TextView.setText(person.getName());amount_TextView.setText(person.getAmount()+"");phone_TextView.setText(person.getPhone());return view;}} }
工具類:查詢所有的記錄,這里省略了數據庫
public List<Person> findAll(){List<Person> persons = new ArrayList<Person>();SQLiteDatabase db = helper.getReadableDatabase();//query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)Cursor cursor = db.query("person", new String[]{"id","name","phone","amount"}, null, null, null, null, null, null);while(cursor.moveToNext()){int id = cursor.getInt(cursor.getColumnIndex("id"));String name = cursor.getString(cursor.getColumnIndex("name"));String phone = cursor.getString(cursor.getColumnIndex("phone"));String amount = cursor.getString(cursor.getColumnIndex("amount"));persons.add(new Person(id,name,phone,Float.valueOf(amount)));}cursor.close();//關閉游標db.close();//關閉數據庫return persons;}轉載于:https://www.cnblogs.com/xushuai123/archive/2013/04/19/3634411.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Android学习 —— 多种适配器方式实现ListView的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设置代码ios中根据文本设置label高
- 下一篇: Android__Context