SimpleAdapter的用法
學習listView的時候,按照例子設定item的布局為系統提供的simple_list_item_single_choice.xml@frameworks/base/core/res/res/layout/ 加上SimpleAdapter,感覺很爽,什么都不用寫直接就用了,然后我就自己定義了一個布局一個ImageView和一個CheckedTextView,問題來了,點擊不選中,但是使用SimpleAdapter的時候可是好好的。我決定肯定是SimpleAdapter做了什么事情可以很好的實現單選(后來發現與simpleadapter完全無關,只是CheckedTextView實現了選擇功能)。于我決定認真的研究一下SimpleAdapter。
SimpleAdapter繼承于BaseAdapter,代碼也不多@frameworks/base/core/java/android/widget/SimpleAdapter.java
最最重要的一個函數是bindView,它被getView調用。它個是它使用拿數據適配組件的關鍵
private void bindView(int position, View view) {final Map dataSet = mData.get(position);if (dataSet == null) {return;}final ViewBinder binder = mViewBinder;final String[] from = mFrom;final int[] to = mTo;final int count = to.length;for (int i = 0; i < count; i++) {final View v = view.findViewById(to[i]);if (v != null) {final Object data = dataSet.get(from[i]);String text = data == null ? "" : data.toString();if (text == null) {text = "";}boolean bound = false; if (binder != null) { //④bound = binder.setViewValue(v, data, text);}if (!bound) {if (v instanceof Checkable) {// ①if (data instanceof Boolean) {((Checkable) v).setChecked((Boolean) data);} else if (v instanceof TextView) {// Note: keep the instanceof TextView check at the bottom of these// ifs since a lot of views are TextViews (e.g. CheckBoxes). setViewText((TextView) v, text);} else {throw new IllegalStateException(v.getClass().getName() +" should be bound to a Boolean, not a " +(data == null ? "<unknown type>" : data.getClass())); }} else if (v instanceof TextView) { //②// Note: keep the instanceof TextView check at the bottom of these// ifs since a lot of views are TextViews (e.g. CheckBoxes). setViewText((TextView) v, text);} else if (v instanceof ImageView) { //③if (data instanceof Integer) {setViewImage((ImageView) v, (Integer) data); } else {setViewImage((ImageView) v, text);}} else {throw new IllegalStateException(v.getClass().getName() + " is not a " +" view that can be bounds by this SimpleAdapter");}}}}}注意我做成紅色標記的這四個點,暫時不管第四個,先說說前三個。
在此之前先看一個SimpleAdapter的用法
new SimpleAdapter(getActivity(),buildData(),R.layout.logo,new String[]{"img","text","check"},new int[]{R.id.logo, R.id.tvListItem,R.id.tvListItem});紅色標記①是給實現Checkable接口的TextView賦值,所以它檢查值的類型,如果是boolean它就明白是設置成選中狀態,如果是TextView就是賦字符值。所以要給CheckedTextView賦值,需要寫兩次就像我上面的例子一樣text和check一個是顯示的內容,一個是批選中狀態,所以下面我寫了兩次R.id.tvListItem。
除些之后它還可以給ImageView賦值,所就是說只要你的控件是由CheckedTextView,TextView和ImageView中的一種或者幾種組合而成,不管個數是多少個,都可以用SimpleAdapter做數據適配。
再看④,這就更牛B了,先看一下ViewBinder的定義
public static interface ViewBinder {boolean setViewValue(View view, Object data, String textRepresentation);}在不用自己實現Adapter的情況下,自定義數據的適配,simpleAdapter的適用范圍又擴大了很多,簡直是萬能的了。自定義一個控件,然后自己實現viewBinder接口,設置到SimpleAdapter中,就可以用它來適配你自己的控件了。
轉載于:https://www.cnblogs.com/gelandesprung/p/4232286.html
總結
以上是生活随笔為你收集整理的SimpleAdapter的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql实时双备
- 下一篇: 逼出的成功,强迫的辉煌