ArrayAdapater 源码展示 :
/*
* 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 android.annotation.ArrayRes;
import android.annotation.IdRes;
import android.annotation.LayoutRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* You can use this adapter to provide views for an {@link AdapterView},
* Returns a view for each object in a collection of data objects you
* provide, and can be used with list-based user interface widgets such as
* {@link ListView} or {@link Spinner}.
* <p>
* By default, the array adapter creates a view by calling {@link Object#toString()} on each
* data object in the collection you provide, and places the result in a TextView.
* You may also customize what type of view is used for the data object in the collection.
* To customize what type of view is used for the data object,
* override {@link #getView(int, View, ViewGroup)}
* and inflate a view resource.
* For a code example, see
* the <a href="https://developer.android.com/samples/CustomChoiceList/index.html">
* CustomChoiceList</a> sample.
* </p>
* <p>
* For an example of using an array adapter with a ListView, see the
* <a href="{@docRoot}guide/topics/ui/declaring-layout.html#AdapterViews">
* Adapter Views</a> guide.
* </p>
* <p>
* For an example of using an array adapter with a Spinner, see the
* <a href="{@docRoot}guide/topics/ui/controls/spinner.html">Spinners</a> guide.
* </p>
* <p class="note"><strong>Note:</strong>
* If you are considering using array adapter with a ListView, consider using
* {@link android.support.v7.widget.RecyclerView} instead.
* RecyclerView offers similar features with better performance and more flexibility than
* ListView provides.
* See the
* <a href="https://developer.android.com/guide/topics/ui/layout/recyclerview.html">
* Recycler View</a> guide.</p>
*/
public class ArrayAdapter<T> extends BaseAdapter implements Filterable, ThemedSpinnerAdapter {
/**
* Lock used to modify the content of {@link #mObjects}. Any write operation
* performed on the array should be synchronized on this lock. This lock is also
* used by the filter (see {@link #getFilter()} to make a synchronized copy of
* the original array of data.
*/
@UnsupportedAppUsage
private final Object mLock = new Object();
private final LayoutInflater mInflater;
private final Context mContext;
/**
* The resource indicating what views to inflate to display the content of this
* array adapter.
*/
private final int mResource;
/**
* The resource indicating what views to inflate to display the content of this
* array adapter in a drop down widget.
*/
private int mDropDownResource;
/**
* Contains the list of objects that represent the data of this ArrayAdapter.
* The content of this list is referred to as "the array" in the documentation.
*/
@UnsupportedAppUsage
private List<T> mObjects;
/**
* Indicates whether the contents of {@link #mObjects} came from static resources.
*/
private boolean mObjectsFromResources;
/**
* If the inflated resource is not a TextView, {@code mFieldId} is used to find
* a TextView inside the inflated views hierarchy. This field must contain the
* identifier that matches the one defined in the resource file.
*/
private int mFieldId = 0;
/**
* Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever
* {@link #mObjects} is modified.
*/
private boolean mNotifyOnChange = true;
// A copy of the original mObjects array, initialized from and then used instead as soon as
// the mFilter ArrayFilter is used. mObjects will then only contain the filtered values.
@UnsupportedAppUsage
private ArrayList<T> mOriginalValues;
private ArrayFilter mFilter;
/** Layout inflater used for {@link #getDropDownView(int, View, ViewGroup)}. */
private LayoutInflater mDropDownInflater;
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource) {
this(context, resource, 0, new ArrayList<>());
}
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId) {
this(context, resource, textViewResourceId, new ArrayList<>());
}
/**
* Constructor. This constructor will result in the underlying data collection being
* immutable, so methods such as {@link #clear()} will throw an exception.
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull T[] objects) {
this(context, resource, 0, Arrays.asList(objects));
}
/**
* Constructor. This constructor will result in the underlying data collection being
* immutable, so methods such as {@link #clear()} will throw an exception.
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId, @NonNull T[] objects) {
this(context, resource, textViewResourceId, Arrays.asList(objects));
}
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@NonNull List<T> objects) {
this(context, resource, 0, objects);
}
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a layout to use when
* instantiating views.
* @param textViewResourceId The id of the TextView within the layout resource to be populated
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId, @NonNull List<T> objects) {
this(context, resource, textViewResourceId, objects, false);
}
private ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId, @NonNull List<T> objects, boolean objsFromResources) {
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = mDropDownResource = resource;
mObjects = objects;
mObjectsFromResources = objsFromResources;
mFieldId = textViewResourceId;
}
/**
* Adds the specified object at the end of the array.
*
* @param object The object to add at the end of the array.
* @throws UnsupportedOperationException if the underlying data collection is immutable
*/
public void add(@Nullable T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
} else {
mObjects.add(object);
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Adds the specified Collection at the end of the array.
*
* @param collection The Collection to add at the end of the array.
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
*/
public void addAll(@NonNull Collection<? extends T> collection) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.addAll(collection);
} else {
mObjects.addAll(collection);
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Adds the specified items at the end of the array.
*
* @param items The items to add at the end of the array.
* @throws UnsupportedOperationException if the underlying data collection is immutable
*/
public void addAll(T ... items) {
synchronized (mLock) {
if (mOriginalValues != null) {
Collections.addAll(mOriginalValues, items);
} else {
Collections.addAll(mObjects, items);
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Inserts the specified object at the specified index in the array.
*
* @param object The object to insert into the array.
* @param index The index at which the object must be inserted.
* @throws UnsupportedOperationException if the underlying data collection is immutable
*/
public void insert(@Nullable T object, int index) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(index, object);
} else {
mObjects.add(index, object);
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Removes the specified object from the array.
*
* @param object The object to remove.
* @throws UnsupportedOperationException if the underlying data collection is immutable
*/
public void remove(@Nullable T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.remove(object);
} else {
mObjects.remove(object);
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Remove all elements from the list.
*
* @throws UnsupportedOperationException if the underlying data collection is immutable
*/
public void clear() {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.clear();
} else {
mObjects.clear();
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Sorts the content of this adapter using the specified comparator.
*
* @param comparator The comparator used to sort the objects contained
* in this adapter.
*/
public void sort(@NonNull Comparator<? super T> comparator) {
synchronized (mLock) {
if (mOriginalValues != null) {
Collections.sort(mOriginalValues, comparator);
} else {
Collections.sort(mObjects, comparator);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
/**
* Control whether methods that change the list ({@link #add}, {@link #addAll(Collection)},
* {@link #addAll(Object[])}, {@link #insert}, {@link #remove}, {@link #clear},
* {@link #sort(Comparator)}) automatically call {@link #notifyDataSetChanged}. If set to
* false, caller must manually call notifyDataSetChanged() to have the changes
* reflected in the attached view.
*
* The default is true, and calling notifyDataSetChanged()
* resets the flag to true.
*
* @param notifyOnChange if true, modifications to the list will
* automatically call {@link
* #notifyDataSetChanged}
*/
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
/**
* Returns the context associated with this array adapter. The context is used
* to create views from the resource passed to the constructor.
*
* @return The Context associated with this adapter.
*/
public @NonNull Context getContext() {
return mContext;
}
@Override
public int getCount() {
return mObjects.size();
}
@Override
public @Nullable T getItem(int position) {
return mObjects.get(position);
}
/**
* Returns the position of the specified item in the array.
*
* @param item The item to retrieve the position of.
*
* @return The position of the specified item.
*/
public int getPosition(@Nullable T item) {
return mObjects.indexOf(item);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public @NonNull View getView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
return createViewFromResource(mInflater, position, convertView, parent, mResource);
}
private @NonNull View createViewFromResource(@NonNull LayoutInflater inflater, int position,
@Nullable View convertView, @NonNull ViewGroup parent, int resource) {
final View view;
final TextView text;
if (convertView == null) {
view = inflater.inflate(resource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(mFieldId);
if (text == null) {
throw new RuntimeException("Failed to find view with ID "
+ mContext.getResources().getResourceName(mFieldId)
+ " in item layout");
}
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
final T item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence) item);
} else {
text.setText(item.toString());
}
return view;
}
/**
* <p>Sets the layout resource to create the drop down views.</p>
*
* @param resource the layout resource defining the drop down views
* @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
*/
public void setDropDownViewResource(@LayoutRes int resource) {
this.mDropDownResource = resource;
}
/**
* Sets the {@link Resources.Theme} against which drop-down views are
* inflated.
* <p>
* By default, drop-down views are inflated against the theme of the
* {@link Context} passed to the adapter's constructor.
*
* @param theme the theme against which to inflate drop-down views or
* {@code null} to use the theme from the adapter's context
* @see #getDropDownView(int, View, ViewGroup)
*/
@Override
public void setDropDownViewTheme(@Nullable Resources.Theme theme) {
if (theme == null) {
mDropDownInflater = null;
} else if (theme == mInflater.getContext().getTheme()) {
mDropDownInflater = mInflater;
} else {
final Context context = new ContextThemeWrapper(mContext, theme);
mDropDownInflater = LayoutInflater.from(context);
}
}
@Override
public @Nullable Resources.Theme getDropDownViewTheme() {
return mDropDownInflater == null ? null : mDropDownInflater.getContext().getTheme();
}
@Override
public View getDropDownView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
final LayoutInflater inflater = mDropDownInflater == null ? mInflater : mDropDownInflater;
return createViewFromResource(inflater, position, convertView, parent, mDropDownResource);
}
/**
* Creates a new ArrayAdapter from external resources. The content of the array is
* obtained through {@link android.content.res.Resources#getTextArray(int)}.
*
* @param context The application's environment.
* @param textArrayResId The identifier of the array to use as the data source.
* @param textViewResId The identifier of the layout used to create views.
*
* @return An ArrayAdapter<CharSequence>.
*/
public static @NonNull ArrayAdapter<CharSequence> createFromResource(@NonNull Context context,
@ArrayRes int textArrayResId, @LayoutRes int textViewResId) {
final CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
return new ArrayAdapter<>(context, textViewResId, 0, Arrays.asList(strings), true);
}
@Override
public @NonNull Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
/**
* {@inheritDoc}
*
* @return values from the string array used by {@link #createFromResource(Context, int, int)},
* or {@code null} if object was created otherwsie or if contents were dynamically changed after
* creation.
*/
@Override
public CharSequence[] getAutofillOptions() {
// First check if app developer explicitly set them.
final CharSequence[] explicitOptions = super.getAutofillOptions();
if (explicitOptions != null) {
return explicitOptions;
}
// Otherwise, only return options that came from static resources.
if (!mObjectsFromResources || mObjects == null || mObjects.isEmpty()) {
return null;
}
final int size = mObjects.size();
final CharSequence[] options = new CharSequence[size];
mObjects.toArray(options);
return options;
}
/**
* <p>An array filter 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.</p>
*/
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
final FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mObjects);
}
}
if (prefix == null || prefix.length() == 0) {
final ArrayList<T> list;
synchronized (mLock) {
list = new ArrayList<>(mOriginalValues);
}
results.values = list;
results.count = list.size();
} else {
final String prefixString = prefix.toString().toLowerCase();
final ArrayList<T> values;
synchronized (mLock) {
values = new ArrayList<>(mOriginalValues);
}
final int count = values.size();
final ArrayList<T> newValues = new ArrayList<>();
for (int i = 0; i < count; i++) {
final T value = values.get(i);
final String valueText = value.toString().toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
for (String word : words) {
if (word.startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<T>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
源码解析 :
首先我们先看顶部:
这里告诉我们以下的几点内容
- ArrayAdapater 可以给ListView 和 Spinner 等 Adapater 的子类进行显示。
- ArrayAdapater 内部的实现方式是获取到需要的数据,然后将数据转换为String 类型的,最后将数据中的值一条一条赋予给内部的textview
- 如果想要自己定义ArraryAdapater 中每条条目显示的内容,如:第7 条之后显示另外的展现方式,那么可以重写getView 的方法进行修改。可以在 https://developer.android.com/samples/CustomChoiceList/index.html查看代码的示例 (经过检测,无法获取代码的实例)
- 可以在 https://developer.android.com/guide/topics/ui/declaring-layout.html 查看 listview 使用 ArrayAdapater 的示例
- 可以在 https://developer.android.google.cn/guide/topics/ui/controls/spinner 查看 Spinners使用 ArrayAdapater 的示例
- 推荐大家将使用 Recyclerview 替换 ListView 进行使用,可以在 https://developer.android.google.cn/guide/topics/ui/layout/recyclerview.html 获得 Recyclerview 的 使用示例。
顶部的介绍看完,我们这里再往下看可以知道
ArrayAdapter 继承了BaseAdapter 并且实现了Filterable,和ThemedSpinnerAdapter 这两个接口
首先,看构造方法:
可以看到最终构造方法会调用到五个参数的方法中
两个参数的构造方法
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource) {
this(context, resource, 0, new ArrayList<>());
}
三个参数的构造方法
注意: 这三个方法都是三个参数的构造方法,但是第三个参数不同
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId) {
this(context, resource, textViewResourceId, new ArrayList<>());
}
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull T[] objects) {
this(context, resource, 0, Arrays.asList(objects));
}
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@NonNull List<T> objects) {
this(context, resource, 0, objects);
}
四个参数的构造方法
又是最后的参数不同
// 这个四个参数的方法调用下方的四个参数的方法
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull T[] objects) {
this(context, resource, 0, Arrays.asList(objects));
}
// 调用五个参数的方法
public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId, @NonNull List<T> objects) {
this(context, resource, textViewResourceId, objects, false);
}
那么我们看五个参数的构造方法中参数所代表的含义
参数1 : context 的对象
参数2 : 子条目的布局id
参数3 : 子条目中想要赋予的textview 的id
参数4 : 子条目需要的内容集合
参数5 : 资源是否来自与静态资源
private ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@IdRes int textViewResourceId, @NonNull List<T> objects, boolean objsFromResources) {
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = mDropDownResource = resource;
mObjects = objects;
mObjectsFromResources = objsFromResources;
mFieldId = textViewResourceId;
}
然后这里就会完成资源的获取,方便之后的内容进行调用
ArrayAdapater 对于BaseAdapater 的封装
上面我们知道在构造方法中,不停的调用最后获取到了所需要的资源,那么我们就回想一下ListView 使用BaseAdapater 中如果想要使用,那么大家需要重写getView getItem getItemId getCount 这几个方法。
这几个方法是什么含义呢?
getView : 获得一个在数据集中指定位置显示数据的视图,我们在这里一般做iteam 条目的复制
getItem : 获得条目的内容
getItemId : 获得条目的id
getCount : 获取条目的数量
那么我们就先从简单的方法看起,在 getCount 方法中只有一句话,返回当前数量的条目
@Override
public int getCount() {
return mObjects.size();
}
之后再看getItemId 方法,也是向我们往常一样,将获取到的postion作为当前的iteamid,进行返回
@Override
public long getItemId(int position) {
return position;
}
之后,继续看getItem 的方法,指的是获取数据中的内容
@Override
public @Nullable T getItem(int position) {
return mObjects.get(position);
}
最后,我们看向 BaseAdapater 中最主要的方法 getView 。他调用了一个名叫 createViewFromResource 的方法,于是我们继续追踪。
@Override
public @NonNull View getView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
return createViewFromResource(mInflater, position, convertView, parent, mResource);
}
这个方法也是特别的简单,首先先判断 convertView 对象是否为null 。如果为null ,那么就创建view 的对象,如果不为null,那么这里就复用 convertView 对象。
接下来这段也很简单,就是找到iteam布局中的textview 的对象,如果找不到就报出异常。当然如果内部没有textview进行复制那么就直接报出异常:ArrayAdapater 的内部必须拥有textview 对象。
最后的内容也特别的简单,就是看获取到的数据是否是字符串类型的如果不是,那么就将他转换为string类型,如果是,就直接给textview 设置值。
private @NonNull View createViewFromResource(@NonNull LayoutInflater inflater, int position,
@Nullable View convertView, @NonNull ViewGroup parent, int resource) {
final View view;
final TextView text;
if (convertView == null) {
view = inflater.inflate(resource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(mFieldId);
if (text == null) {
throw new RuntimeException("Failed to find view with ID "
+ mContext.getResources().getResourceName(mFieldId)
+ " in item layout");
}
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
final T item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence) item);
} else {
text.setText(item.toString());
}
return view;
}
ArrayAdapater 对于 Filterable 的实现
我们在上面的时候可以知道,ArrayAdapater 实现了 Filterable 这个接口,那么我们看一下 Filterable 。
从这里我们可以知道 Filterable 这个接口的作用就是过滤 AdapaterView 的条件。那么我们就知道,ArrayAdapater 实现这个接口的作用就是过滤内部的内容。
使用示例:
上面说完了使用的情况,那么我们就看一下这个是如何使用的。
class SimpleActivity : BaseActivity<ActivitySimpleBinding>() {
var datras: Array<Any>? = null
override fun getLayoutIDS(): Int {
return R.layout.activity_simple
}
override fun initView() {
// 准备数据
datras = Array(50) {
when {
it < 10 -> "赵氏孤儿"
it < 20 -> "杨门虎将"
it < 30 -> "康熙大帝"
else -> "大清帝国"
} }
// 创建 Adapater
val adapater = object : ArrayAdapter<Any>( MyApp.context as Context, R.layout.iteam_simple, datras as Array<Any> ) { }
// 将Adapater 设置给listview
mBinding?.avfSimpleFilpper?.adapter = adapater
// 设置edittext 的监听
mBinding?.etSimpleInput?.addTextChangedListener(
object :TextWatcher{
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(
s: CharSequence?,start: Int, count: Int, after: Int ) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// adapater 使用过滤器
adapater.filter.filter(s)
}
}
)
}
}
具体的实现:
上面使用的代码特别的简单,就是给 listview 设置数据,然后对editext 的输入结果进行监听,最后通过 adapater.filter.filter(cs) 过滤输入的内容。
我们知道他如何使用了,那么我们就去看一下 ArrayAdapater 是如何实现的。
我们先看Filterable 接口, 就只有一个 getFilter 方法。
package android.widget;
/**
* <p>Defines a filterable behavior. A filterable class can have its data
* constrained by a filter. Filterable classes are usually
* {@link android.widget.Adapter} implementations.</p>
*
* @see android.widget.Filter
*/
public interface Filterable {
/**
* <p>Returns a filter that can be used to constrain data with a filtering
* pattern.</p>
*
* <p>This method is usually implemented by {@link android.widget.Adapter}
* classes.</p>
*
* @return a filter used to constrain data
*/
Filter getFilter();
}
看来了Filterable ,我们去看 ArrayAdapater 的 getFilter 方法 。
@Override
public @NonNull Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
判断 mFilter 是否为空如果为空,就创建 ArrayFilter ,否则的话就复用数据。看到这里,我们继续去看 ArrayFilter 是什么?
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
final FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mObjects);
}
}
if (prefix == null || prefix.length() == 0) {
final ArrayList<T> list;
synchronized (mLock) {
list = new ArrayList<>(mOriginalValues);
}
results.values = list;
results.count = list.size();
} else {
final String prefixString = prefix.toString().toLowerCase();
final ArrayList<T> values;
synchronized (mLock) {
values = new ArrayList<>(mOriginalValues);
}
final int count = values.size();
final ArrayList<T> newValues = new ArrayList<>();
for (int i = 0; i < count; i++) {
final T value = values.get(i);
final String valueText = value.toString().toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
for (String word : words) {
if (word.startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<T>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
大家可以发现 ArrayFilter 是 Filter 的子类。并且重写了 performFiltering 和 publishResults 的方法。
通过访问 Fifter 方法大家会知道 performFiltering 是 执行过滤的方法,publishResults 是得到过滤结果的方法。
我们这里就知道了,那么肯定是获取输入的内容,然后获取到第一个字,然后再输出结果。
大致思路知道了,那么我们就去看一下具体的实现流程。(毕竟会说的未必会写)
performFiltering 方法解析
在 performFiltering 方法中,说先创建 FilterResults 的对象。然后判断 原始mObjects数组的副本 是否为null,如果为null,那么就加锁创建对象。
大家上面了解到了performFiltering是执行过滤的方法,那么他所需要的参数 prefix 那么就是输入的原始内容。
这里是在判断输入的内容是否为空,如果为空的话就将所有的数据全部添加到FilterResults中,最后一期返回。
如果返回的数据部位null的话,那么就 先获取到内容,然后将内容转化为小写(toLowerCase方法之后获取到原先的内容,但是却不会改变原内容),然后创建一个集合,并且将原先的数据放进去。获取到这个数组的长度后,再次创建一个新的数组,遍历第一个数组,如果第一个数组中的内容是以输入的内容开头(else 中是判断如果集合数据如果以空格开头,那么也以空格之后的内容计算),最后将数据添加到新的集合中,返回回去。
publishResults 方法解析
publishResults 的方法内容如下
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<T>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
特别简单,就是获取数据刷新界面。
上面看完了BaseAdapter 与 Filterable ,那么我们继续看 ThemedSpinnerAdapter 这个接口。
package android.widget;
import android.annotation.Nullable;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.view.View;
import android.view.ViewGroup;
/**
* An extension of SpinnerAdapter that is capable of inflating drop-down views
* against a different theme than normal views.
* <p>
* Classes that implement this interface should use the theme provided to
* {@link #setDropDownViewTheme(Theme)} when creating views in
* {@link SpinnerAdapter#getDropDownView(int, View, ViewGroup)}.
*/
public interface ThemedSpinnerAdapter extends SpinnerAdapter {
/**
* Sets the {@link Resources.Theme} against which drop-down views are
* inflated.
*
* @param theme the context against which to inflate drop-down views, or
* {@code null} to use the default theme
* @see SpinnerAdapter#getDropDownView(int, View, ViewGroup)
*/
void setDropDownViewTheme(@Nullable Resources.Theme theme);
/**
* Returns the value previously set by a call to
* {@link #setDropDownViewTheme(Theme)}.
*
* @return the {@link Resources.Theme} against which drop-down views are
* inflated, or {@code null} if one has not been explicitly set
*/
@Nullable
Resources.Theme getDropDownViewTheme();
}
大家可以看到 ThemedSpinnerAdapter 继承了 SpinnerAdapter ,然后再里面有两个方法需要子类实现。看完大概的形成我们去看他的介绍。
就说说他是SpnnerAdapater 的子类,扩展了SpnnerAdapater 的主题。再去看 SpinnerAdapter 这个类。
package android.widget;
import android.view.View;
import android.view.ViewGroup;
/**
* Extended {@link Adapter} that is the bridge between a
* {@link android.widget.Spinner} and its data. A spinner adapter allows to
* define two different views: one that shows the data in the spinner itself
* and one that shows the data in the drop down list when the spinner is
* pressed.
*/
public interface SpinnerAdapter extends Adapter {
/**
* Gets a {@link android.view.View} that displays in the drop down popup
* the data at the specified position in the data set.
*
* @param position index of the item whose view we want.
* @param convertView the old view to reuse, if possible. Note: You should
* check that this view is non-null and of an appropriate type before
* using. If it is not possible to convert this view to display the
* correct data, this method can create a new view.
* @param parent the parent that this view will eventually be attached to
* @return a {@link android.view.View} corresponding to the data at the
* specified position.
*/
public View getDropDownView(int position, View convertView, ViewGroup parent);
}
这个类从名字上就可以看的出来是为了Spnner这个控件准备的适配器,在这个方法中只有一个getDropDownView 的方法。
看完之后大家知道,ArrayAdapater 需要实现三个方法。
还是像上次的一样,先看demo,再说源码。当然了,代码就不说了,还和之前一样,只是将listview 换为了Spnner。直接上效果:
源码: 和Spnner有关的源码为
@Override
public View getDropDownView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
final LayoutInflater inflater = mDropDownInflater == null ? mInflater : mDropDownInflater;
return createViewFromResource(inflater, position, convertView, parent, mDropDownResource);
}
@Override
public @Nullable Resources.Theme getDropDownViewTheme() {
return mDropDownInflater == null ? null : mDropDownInflater.getContext().getTheme();
}
@Override
public void setDropDownViewTheme(@Nullable Resources.Theme theme) {
if (theme == null) {
mDropDownInflater = null;
} else if (theme == mInflater.getContext().getTheme()) {
mDropDownInflater = mInflater;
} else {
final Context context = new ContextThemeWrapper(mContext, theme);
mDropDownInflater = LayoutInflater.from(context);
}
}
@Override
public @Nullable Resources.Theme getDropDownViewTheme() {
return mDropDownInflater == null ? null : mDropDownInflater.getContext().getTheme();
}
getDropDownView 方法的调用流程是:先获取 inflater 的对象,然后再调用createViewFromResource 方法创建布局。(createViewFromResource 之前的时候分析过,只是创建textview 的对象,然后设置值。具体请看之前)
然后其他的两个方法就是特别简单的set、get 方法,只不过做了一些判断。
在ArrayAdapater 中其他的方法,大家可以看一下。我感觉没有什么难的(就是添加、删除等方法)。
上面的分析就到此告一段落,我们这里说一些题外话。
2020年,这是一个不同的时候。在刚刚过年的时候,就发生了疫情。但是全国人民心往一起走,患难与共。大的企业给湖北捐款,捐物。小的企业,自觉支持疫情,防止疫情。美丽的医护人员(我不是说体态的美丽,而是心灵的完美)毅然决然的冲锋在最前线。
我相信中国一定会马上好起来,然后在康复之后,定然会像老话(福兮祸之所倚祸兮福之所伏)说的一样更加强大。
中国!加油!