溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

多布局適配器如何讓ListView能夠呈現(xiàn)多種布局

發(fā)布時間:2021-11-26 11:32:02 來源:億速云 閱讀:116 作者:柒染 欄目:移動開發(fā)

本篇文章給大家分享的是有關(guān)多布局適配器如何讓ListView能夠呈現(xiàn)多種布局,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

ListView用了SimpleAdapter之后就只能呈現(xiàn)一種Layout,這樣雖然簡單但是有時不能滿足需求。所以,我下載SDK的源碼重寫了SimpleAdapter,你可以看出那些JavaDoc還是之前SimpleAdapter的JavaDoc。

各位下載了之后能將它當成SimpleAdapter使用。

主要修改的地方是:

1、構(gòu)造方法不再接受單個Layout Resource,能接受Resource數(shù)組。

2、能夠根據(jù) ItemViewType來選擇Resource,所以子類應(yīng)該要重寫  getItemViewType 和 getViewTypeCount(可選)。

? /*  * Copyright (C) 2006 The Android Open Source Project  *  * Licensed under the Apache License, Version 2.0 (the "License");  * you may not use this file except in compliance with the License.  * You may obtain a copy of the License at  *  *      http://www.apache.org/licenses/LICENSE-2.0  *  * Unless required by applicable law or agreed to in writing, software  * distributed under the License is distributed on an "AS IS" BASIS,  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  * See the License for the specific language governing permissions and  * limitations under the License.  */  package android.widget;  import java.util.ArrayList; import java.util.List; import java.util.Map;  import android.content.Context; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Checkable; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView;  /**  * 這是一個簡單的適配器,可以將靜態(tài)數(shù)據(jù)映射到XML文件中定義好的視圖.  * 你可以將 Maps 的 ArrayList 指定為用于列表的數(shù)據(jù).ArrayList 中的每一項對應(yīng)列表中的一行.  * Maps 中包含用于一行的數(shù)據(jù).你也可以指定 XML 文件,其中定義了用于顯示行的視圖,通過  * Map 的關(guān)鍵字映射到指定的視圖.  * 綁定數(shù)據(jù)到視圖分兩個階段.首先,如果 {@link android.widget.SimpleAdapter.ViewBinder} 是有效的,  * 則調(diào)用 {@link ViewBinder#setViewValue(android.view.View, Object, String)} 方法.  * 如果返回值為真,則執(zhí)行綁定.如果返回值為假,則按以下順序綁定視圖:  *    *  實現(xiàn)了 Checkable 的視圖(例如 CheckBox),期望綁定值是布爾類型.  *  TextView,期望綁定值是字符串類型,通過調(diào)用 {@link #setViewText(TextView, String)} 綁定.  *  ImageView,期望綁定值是資源 ID 或者一個字符串,通過調(diào)用  * {@link #setViewImage(ImageView, int)} 或 {@link #setViewImage(ImageView, String)}綁定.  *  * 如果沒有合適的綁定發(fā)生,將會拋出 {@link IllegalStateException} 異常.  * @author translate by 德羅德  * @author convert by cnmahj  */ public class MultiLayoutSimpleAdapter extends BaseAdapter implements Filterable {     private int[] mTo;     private String[] mFrom;     private ViewBinder mViewBinder;      protected Listextends Map     private int[] mResources;     private int[] mDropDownResources;     private LayoutInflater mInflater;      private SimpleFilter mFilter;     private ArrayList     /**      * 構(gòu)造函數(shù)      *      * @param context 與 SimpleAdapter 關(guān)聯(lián)的運行著的視圖的上下文.      * @param data Map 的列表.列表中的每個條目對應(yīng)一行.Maps 中包含所有在 from 中指定的數(shù)據(jù).      * @param resource 定義列表項目的視圖布局的資源 ID.布局文件至少應(yīng)該包含在 to 中定義了的名稱.      * @param from 與 Map 中的項目建立關(guān)聯(lián)的列名的列表.      * @param to 用于顯示 from 中參數(shù)中的列的視圖列表.這些視圖應(yīng)該都是 TextView 類型的.      * 該列表中的第 N 個視圖顯示從參數(shù) from 中的第 N 列獲取的值.      */     public MultiLayoutSimpleAdapter(Context context, Listextends Map            int[] resources, String[] from, int[] to) {         mData = data;         mResources = mDropDownResources = resources;         mFrom = from;         mTo = to;         mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);     }      @Override     public int getViewTypeCount() {         return mResources.length;     }      /**      * @see android.widget.Adapter#getCount()      */     public int getCount() {         return mData.size();     }      /**      * @see android.widget.Adapter#getItem(int)      */     public Object getItem(int position) {         return mData.get(position);     }      /**      * @see android.widget.Adapter#getItemId(int)      */     public long getItemId(int position) {         return position;     }      /**      * @see android.widget.Adapter#getView(int, View, ViewGroup)      */     public View getView(int position, View convertView, ViewGroup parent) {         return createViewFromResource(position, convertView, parent, mResources[getItemViewType(position)]);     }           private View createViewFromResource(int position, View convertView,             ViewGroup parent, int resource) {         View v;         if (convertView == null) {             v = mInflater.inflate(resource, parent, false);         } else {             v = convertView;         }          bindView(position, v);          return v;     }      /**      * 設(shè)置創(chuàng)建下拉列表視圖的布局資源 ID.      *      * @param resource 定義下拉列表視圖的布局資源 ID.      * @see #getDropDownView(int, android.view.View, android.view.ViewGroup)      */     public void setDropDownViewResource(int[] resources) {         this.mDropDownResources = resources;     }      @Override     public View getDropDownView(int position, View convertView, ViewGroup parent) {         return createViewFromResource(position, convertView, parent, mResources[getItemViewType(position)]);     }      private void bindView(int position, View view) {         final Map        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 ? " : 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 if (v instanceof Spinner) {                         if (data instanceof Integer) {                             ((Spinner)v).setSelection((Integer) data);                         } else {                             continue;                         }                     } else {                         throw new IllegalStateException(v.getClass().getName() + " is not a " +                                 " view that can be bounds by this SimpleAdapter");                     }                 }             }         }     }      /**      * 返回用于將數(shù)據(jù)綁定到視圖的 {@link ViewBinder}.      *      * @return ViewBinder,如果綁定器不存在則返回 null.      *      * @see #setViewBinder(android.widget.SimpleAdapter.ViewBinder)      */     public ViewBinder getViewBinder() {         return mViewBinder;     }      /**      * 設(shè)置用于將數(shù)據(jù)綁定到視圖的綁定器.      *      * @param viewBinder 用于將數(shù)據(jù)綁定到視圖的綁定器.設(shè)置為 null,可以刪除既存的綁定器.      *      * @see #getViewBinder()      */     public void setViewBinder(ViewBinder viewBinder) {         mViewBinder = viewBinder;     }      /**      * 由 bindView() 方法調(diào)用,用于為 ImageView 設(shè)置圖像.只在      * ViewBinder 不存在或者既存的 ViewBinder 無法處理 ImageView 的綁定時才調(diào)用.      *      * 如果調(diào)用 {@link #setViewImage(ImageView, String)} 方法時提供的      * value 參數(shù)可以轉(zhuǎn)換為整數(shù)類型,則會自動調(diào)用本方法.      *      * @param v 接收圖像的 ImageView.      * @param value 從數(shù)據(jù)集獲取到的值      *      * @see #setViewImage(ImageView, String)      */     public void setViewImage(ImageView v, int value) {         v.setImageResource(value);     }      /**      * 由 bindView() 方法調(diào)用,用于為 ImageView 設(shè)置圖像.只在      * ViewBinder 不存在或者既存的 ViewBinder 無法處理 ImageView 的綁定時才調(diào)用.      *      * 本方法默認將 value 作為圖像資源 ID 來對待;當 value      * 無法變換為整數(shù)類型時,才作為圖像的 Uri 來使用.      *      * @param v 接收圖像的 ImageView.      * @param value 從數(shù)據(jù)集獲取到的值.      *      * @see #setViewImage(ImageView, int)      */     public void setViewImage(ImageView v, String value) {         try {             v.setImageResource(Integer.parseInt(value));         } catch (NumberFormatException nfe) {             v.setImageURI(Uri.parse(value));         }     }      /**      * 由 bindView() 方法調(diào)用,用于為 TextView 設(shè)置文本.只在      * ViewBinder 不存在或者既存的 ViewBinder 無法處理 TextView 的綁定時才調(diào)用.      *      * @param v 接收文本的 TextView.      * @param text 設(shè)置到 TextView 的文本.      */     public void setViewText(TextView v, String text) {         v.setText(text);     }      public Filter getFilter() {         if (mFilter == null) {             mFilter = new SimpleFilter();         }         return mFilter;     }      /**      * 該類用于 SimpleAdapter 的外部客戶將適配器的值綁定到視圖.      *      * 你可以使用此類將 SimpleAdapter 不支持的值綁定到視圖,或者改變 SimpleAdapter      * 支持的視圖的綁定方式.      *      * @see MultiLayoutSimpleAdapter#setViewImage(ImageView, int)      * @see MultiLayoutSimpleAdapter#setViewImage(ImageView, String)      * @see MultiLayoutSimpleAdapter#setViewText(TextView, String)      */     public static interface ViewBinder {         /**          * 綁定指定的數(shù)據(jù)到指定的視圖.          *          * 當使用 ViewBinder 綁定了數(shù)據(jù)時,必須返回真.如果該方法返回假,          * SimpleAdapter 會用自己的方式去綁定數(shù)據(jù).          *          * @param view 要綁定數(shù)據(jù)的視圖          * @param data 綁定用的數(shù)據(jù)          * @param textRepresentation 代表所提供的數(shù)據(jù)的安全字符串:          *        或者是 data.toString(),或者是空串,不能為空.          *          * @return 如果將數(shù)據(jù)綁定到了視圖,返回真;否則返回假.          */         boolean setViewValue(View view, Object data, String textRepresentation);     }      /**      * An array filters constrains the content of the array adapter with     * a prefix. Each item that does not start with the supplied prefix      * is removed from the list.      */     private class SimpleFilter extends Filter {          @Override         protected FilterResults performFiltering(CharSequence prefix) {             FilterResults results = new FilterResults();              if (mUnfilteredData == null) {                 mUnfilteredData = new ArrayList            }              if (prefix == null || prefix.length() == 0) {                 ArrayList                results.values = list;                 results.count = list.size();             } else {                 String prefixString = prefix.toString().toLowerCase();                  ArrayList                int count = unfilteredValues.size();                  ArrayList                 for (int i = 0; i < count; i++) {                     Map                    if (h != null) {                          int len = mTo.length;                          for (int j=0; j                            String str =  (String)h.get(mFrom[j]);                              String[] words = str.split(" ");                             int wordCount = words.length;                              for (int k = 0; k < wordCount; k++) {                                 String word = words[k];                                  if (word.toLowerCase().startsWith(prefixString)) {                                     newValues.add(h);                                     break;                                 }                             }                         }                     }                 }                  results.values = newValues;                 results.count = newValues.size();             }              return results;         }          @Override         protected void publishResults(CharSequence constraint, FilterResults results) {             //noinspection unchecked             mData = (List            if (results.count > 0) {                 notifyDataSetChanged();             } else {                 notifyDataSetInvalidated();             }         }     } }

以上就是多布局適配器如何讓ListView能夠呈現(xiàn)多種布局,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI