尝试使用以下方法:
创建一个使用包含 Json 对象的 JsonArray 的 ListView 。由于某种原因, 'public View getView(int position, View convertView, ViewGroup parent)' 代码被触发的次数比 jsonarray 中的内容多。
我做了一个控制测试来检查这一点,我发现即使在 jsonarray 中只有 1 个 Jsonobject,我也想出了 32 次 getView 代码被激活。
我很困惑为什么会这样,因为我的 friend 已经设法制作了与我类似的代码,但没有我遭受的大量激活。我是不是很慢,这是因为单个 Jsonobject 不仅有图像和文本,还有大约 15 个其他项目?还是其他原因?
如果对此有任何帮助,我将不胜感激,我在下面发布了适配器代码:
public class ArticleAdapter extends BaseAdapter{
private JSONArray items;
private Context cont;
public ArticleAdapter(Context context, JSONArray array)
{
super();
this.items = array;
this.cont = context;
}
@Override
public int getCount() {
return items.length();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
WebIView sath;
TextView sati;
Log.i("Seiji", "Checking! " + position);
try
{
if(!items.isNull(position))
{
JSONObject item = items.getJSONObject(position);
if (v == null) {
v = LayoutInflater.from(cont).inflate(R.layout.saved_articles_listitem, null);
}
sath = (WebIView) v.findViewById(R.id.sathumbnail);
sati = (TextView) v.findViewById(R.id.satitle);
if(item.has("image") && sath != null)
{
JSONObject thisImage = item.getJSONObject("image");
sath.reset();
sath.setImageUrl(thisImage.getString("thumbnail"));
sath.loadImage();
}
if(sati != null)
{
sati.setText(item.getString("title"));
}
}else{
return null;
}
}
catch(Exception e)
{
Log.e("num", "Saved Art Error! " + e.toString());
}
return v;
}
}
激活这个类的代码如下:
ListView savedArtList = (ListView) sav.findViewById(R.id.savelist);
ArticleAdapter savedadapter = new ArticleAdapter(cont, flip);
ArtList.setAdapter(savedadapter);
编辑:
多亏了一些非常有用的建议,我才能够找出问题所在。每次添加新行时,Listview 都会自行调整大小,因为我已将 View 高度设置为“wrap_content”。我没有意识到这会导致问题,但是一旦我将它设置为“fill_parent”(或其他情况下的设置值),问题就消失了,我再也没有这个问题了。 再次感谢您提供的有用建议!
最佳答案
getView 将被调用多次 - 布局 ListView 时每个可见单元格,绘制 ListView 时每个可见单元格 + 更多。这是正常行为,getView 应该是有效的。您的图像和/或文本可能会在加载时使每个单元格的高度发生变化,这意味着其他单元格可能变得可见/离开屏幕等。
关于Android:JSONArray & JSONObject 到 ListView 奇怪的读数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8150350/