Java 如何重写ArrayAdapter add方法以向其中添加图像和文本视图?我有自定义的数组适配器类
当我初始化适配器对象并将其设置为listview适配器时,我成功地添加了带有文本的图像,但当我从internet获取更多包含图像的数据时,我希望向其添加更多项。我正在使用json从internet检索信息,其中包括图像url。 这是我的适配器代码Java 如何重写ArrayAdapter add方法以向其中添加图像和文本视图?我有自定义的数组适配器类,java,android,json,listview,android-listview,Java,Android,Json,Listview,Android Listview,当我初始化适配器对象并将其设置为listview适配器时,我成功地添加了带有文本的图像,但当我从internet获取更多包含图像的数据时,我希望向其添加更多项。我正在使用json从internet检索信息,其中包括图像url。 这是我的适配器代码 public class CustomList extends ArrayAdapter<String>{ private final Activity context; private final String[] we
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomList(Activity context,
String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
公共类CustomList扩展了ArrayAdapter{
私人最终活动背景;
私有最终字符串[]web;
私有最终整数[]imageId;
公共自定义列表(活动上下文,
字符串[]web,整数[]imageId){
super(上下文、R.layout.list_single、web);
this.context=上下文;
this.web=web;
this.imageId=imageId;
}
@凌驾
公共视图getView(内部位置、视图视图、视图组父视图){
LayoutInflater充气器=上下文。getLayoutInflater();
视图行视图=充气机。充气(R.layout.list_single,null,true);
TextView txtTitle=(TextView)rowView.findViewById(R.id.txt);
ImageView ImageView=(ImageView)rowView.findViewById(R.id.img);
setxt(web[位置]);
setImageResource(imageId[位置]);
返回行视图;
}
}
设置数组适配器后,我想向其中添加更多项。(带文本的图像)我只知道如何添加文本 首先,我建议对
字符串
和整数
对象使用数组列表
,而不是普通数组。有了它,您可以更轻松地附加数据
在活动
中,保留对传递给适配器的字符串
和整数
数组列表
对象的引用。当您收到新日期时,只需将此数据添加到列表中即可
更新数据时,应调用适配器的notifyDataSetChanged()
方法在视图中显示数据
--编辑--
另一个建议是:您应该回收已经在getView
方法中创建的视图。您可以通过检查提供的contentview(第二个参数)是否为null来实现这一点。这将大大提高较大的列表视图的性能
public View getView(int position, View view, ViewGroup parent) {
if(view == null){
LayoutInflater inflater = context.getLayoutInflater();
view= inflater.inflate(R.layout.list_single, null, true);
}
TextView txtTitle = (TextView) view.findViewById(R.id.txt);
ImageView imageView = (ImageView) view.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return view;
}
在
getView
方法的开头尝试以下操作:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView= inflater.inflate(R.layout.list_single, null); //Try both with ", true" and without.
另外,尝试构建一个可绘制对象并将其传递给
imageView.setImageResource(..)代码>当您收到更多数据时,在适配器上调用“notifyDataSetChanged()。非常感谢。