解压器和循环未按预期工作

4

我正在为 Android 应用程序制作自定义视图时遇到问题,我知道有很多关于 LayoutInflater 的问题,但是我无法解决这个问题。

LayoutInflater 运行正常,但是它应该执行循环 3 次,但只执行了 1 次,因此在最终布局中只得到一个视图。

代码的相关部分如下:

 void populate(String strcline, String url){
lLfD = (LinearLayout)findViewById(R.id.lLfD);

    try{

    JSONArray a1 = new JSONArray(strcline);

    for(int i = 0; i < a1.length(); i++){

        JSONArray a2 =  a1.getJSONArray(i);

        final String fUserId = a2.getString(0);
        String userName = a2.getString(1);
        String userPicture = url + a2.getString(2);


        View child = getLayoutInflater().inflate(R.layout.cellevery, lLfD);
        ImageView avatar = (ImageView)findViewById(R.id.cellAvatar);
        downloadFile(userPicture, avatar);
        TextView cellName = (TextView)findViewById(R.id.cellName);
        cellName.setText(userName);


        lLfD.addView(child);

    }
    }catch(Exception e){

    }
    pDialog.dismiss();

}

1个回答

3

看起来你需要在被膨胀的视图上运行findViewById,否则它只会找到循环中的第一个,而这只是第一个:

   View child = getLayoutInflater().inflate(R.layout.cellevery, lLfD);
    ImageView avatar = (ImageView)child.findViewById(R.id.cellAvatar);
    downloadFile(userPicture, avatar);
    TextView cellName = (TextView)child.findViewById(R.id.cellName);
    cellName.setText(userName);

在您的循环中,findViewById的解释如下:
Loop 1:
1LfD->child1->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds this one)

Loop 2:

1Lfd->
   child1->R.id.cellAvatar
   child2->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds the child1.cellAvatar again)

Loop 3:
1LfD->
   child1->R.id.cellAvatar 
   child2->R.id.cellAvatar 
   child3->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds the child1.cellAvatar again)

通过使用 child.findViewById(R.id.cellAvatar),它确保你为循环的每次运行找到正确的 R.id.cellAvatar。
这样说清楚了吗?
更新2:
当你调用:
getLayoutInflater().inflate(R.layout.cellevery, lLfD);

由于您已将父视图作为第二个参数设置,因此不需要调用以下方法:

lLfD.addView(child);

非常感谢您抽出时间回复。很抱歉,我是Android开发的新手,这是我第一次在没有适配器的情况下使用Inflater,能否请您进一步解释您的答案? - David
findViewById会找到第一个带有R.id.cellAvatar的视图,在你的第二个循环中,findViewById(不带child.)会找到第一个循环中的R.id.cellAvatar,第三个循环也是如此,以此类推。 - Chuck D
所以我应该在循环外膨胀,然后填充视图吗? - David
不,inflater 设计用于在循环内工作。findViewById 只会找到您传入的 R.id 的第一个视图。由于您正在填充自定义视图,因此在您的活动中会多次找到 R.id.cellAvatar,因此它会不断地找到第一个。请查看我的更新答案,让我知道是否有帮助? - Chuck D
感谢您的更新,我已按照您建议进行了修改,但仍然出现相同的问题。不过根据您的逻辑,如果我将“avatar”字段和“cellname”更改为(0)的ID,则可以完美地解决问题,我从这个问题[链接]中得到了灵感(http://stackoverflow.com/questions/6839998/android-using-inflater-only-first-item-of-the-list-gets-correctly-populated)。 - David
是的,这样做的效果是一样的...通过调用child.findViewById,它只会从子视图中进行搜索,而不是整个活动的视图层次结构。我在我的更新2中也发表了另一个评论。 - Chuck D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接