开发者社区 问答 正文

Inflater和循环不起作用

已解决

在我app上的自定义视图上有问题,我知道这个很可能是和inflaters有关系,但是我不知道怎么解决。
inflater刚刚还是好的,但是它应该是做三次循环,现在却只有一次,这样在我最终布局上我只能得到一个view
相关部分代码是下边这个
screenshot

展开
收起
蛮大人123 2016-02-15 11:00:13 2126 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    采纳回答

    看起来好像你只是需要在inflated视图上运行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
    当你调用:
    getLayoutInflater().inflate(R.layout.cellevery, lLfD);
    你已经设置了parent view作为第二参数,所以你不需要调用:
    lLfD.addView(child);

    2019-07-17 18:43:03
    赞同 展开评论
问答地址: