Android 使用ArrayAdapter 加载Bean数据

在Android中 我们经常使用到ListView GridViewRecyclerView,Adapter 通常是继承自BaseAdapter/RecyclerView.Adapter
但开发中也可能需要展示的数据只有一个标题或者属性,自定义Adapter显得有些囊肿,但ArrayAdaprer 很多资料都是使用ArrayList 进行数据描述,但这样可扩展性很差

下面教大家如何正确使用ArrayAdapter

private ArrayList mDatas; if (mDatas != null && !mDatas.isEmpty()) { mListView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, mDatas)); }

如果我们这样使用自定义的Bean类 会输出对象的信息
这不是我们要的
但有什么方法呢我们看一下源码
getView方法:
@Override public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return createViewFromResource(mInflater, position, convertView, parent, mResource); }

这是具体的实现 首先查找这个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); 如果传递过来的对象是CharSequenceorString 类型 就直接设置文本 if (item instanceof CharSequence) { text.setText((CharSequence) item); } else { 否则就设置对象的toString方法 text.setText(item.toString()); }return view; }



看到这 是否恍然大悟了呢如果传递过来的对象就是该对象的toString
但我们一般Bean类都不会复写toStirng方法 而是调用Object 默认是对象的hash值

但我们可以复写toString()方法来正确使用
也就是实体类中 重写toString()方法返回我们想要的字段 比如 name , type
这个toString()返回的就是我们想要在ArrayAdapter里面显示的内容 返回想要显示信息的字段即可

【Android 使用ArrayAdapter 加载Bean数据】QQ643200732

    推荐阅读