4

我目前正在为 android 上的应用程序执行自定义视图时遇到问题,我知道有很多与充气机相关的问题,但我无法解决这个问题。

充气机我工作得很好,但它应该循环 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();

}

4

1 回答 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);
于 2012-12-21T02:31:46.427 回答