有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java充气器和循环不能正常工作

我有一个自定义视图的问题,我目前正在为安卓上的应用程序做,我知道有很多问题与充气机有关,但我无法回避这个问题

充气机我工作得很好,但它应该做了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) 个答案

  1. # 1 楼答案

    看起来您只需要在膨胀视图上运行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);