簡體   English   中英

Inflater和循環不能正常工作

[英]Inflater and loop not working as it should

我有一個自定義視圖的問題,我目前正在為Android上的應用程序做,我知道有很多與inflaters相關的問題,但我無法解決這個問題。

inflater我工作得很好,但它應該做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();

}

您看起來只需要在膨脹的視圖上運行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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM