2015-05-05 81 views
0

我有一個列表視圖,我想透露更多的信息幾個按鈕。我有一個帶有幾個嵌套LinearLayout的佈局的xml文件。當按下「評論」按鈕時,我想讓適當的佈局出現然後消失。在模型對象的內部,我會跟蹤視圖是否被泄露。Android的ListView適配器與getView中的按鈕,改變佈局

public View getView(int position, View convertView, ViewGroup parent) { 
    final CarmenGrade grade = (CarmenGrade) getItem(position); 
    convertView = mInflater.inflate(R.layout.carmen_grade_item, null); 
    commentsLayout = (LinearLayout) convertView.findViewById(R.id.commentsLayout); 
    commentsButton = (Button) convertView.findViewById(R.id.commentsButton); 

    commentsButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (grade.isShowingComments() == true) { 
        commentsLayout.setVisibility(View.GONE); 
        grade.setShowingComments(false); 
        /* other similar layout parts cut */ 
       } else { 
        commentsLayout.setVisibility(View.VISIBLE); 
        grade.setShowingComments(true); 
        /* other similar layout parts cut */ 
       } 
       notifyDataSetChanged(); 
      } 
     }); 
} 

在Android 4.x上,它工作在第一次按下並且正確的佈局變得可見。再次按下按鈕看起來並不一致。偶爾它會消失。

在Android 5.0,我得到了很多的警告,儘管它似乎工作的大部分時間:

W/View﹕ requestLayout() improperly called by android.widget.TextView{2d2581cb V.ED.... ......ID 0,57-231,114 #7f0a0086 app:id/weightedValueTextView} during layout: running second layout pass 

所以我的問題是 - 我怎樣才能使用列表中的項目內getView改變佈局,它始終如一地工作,不會拋出錯誤?我是否錯過了另一個超級明顯的模式?

編輯 對不起,忘了放在我初始化評論佈局的地方。這絕對是。

+1

初始化註釋佈局的位置? – Triode

+0

'commentsLayout'已初始化? – RediOne1

+0

對不起,忘了包括那部分。佈局已初始化並且非空。 – cfihelp

回答

2

在Adapter中,getView()函數被多次調用。所以當你去查找carmen_grade_item裏面的監聽器時,它會返回你在上一次啓動的對象(它的方法可能指向列表視圖中其他行的同一對象)。如果你想使用它您的適配器類中

因此,要克服這個問題保持特定行的viewHolder到數組。或找到具體的佈局,如clickedView.getParent().findViewById(R.id.someLayout);然後執行您的操作。

所以,你的聽衆是這樣

commentsButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

         LinearLayout layout=(LinearLayout) ((MainParent which contains child) 
v.getParent()).findViewById(R.id.commentsLayout); 

         if(layout.isShown()){ 
          layout.setVisibility(View.GONE); 
         }else{ 
          layout.setVisibility(View.VISIBLE); 
         } 


        notifyDataSetChanged(); 
       } 
      }); 
+0

這個變體仍然產生5.0的警告,現在當我第二次點擊按鈕使視圖消失時,它崩潰,說佈局爲null 。這幾乎就好像它沒有正確更新視圖。 – cfihelp

+0

您是否在您的XML或運行時中啓用了fastScroll到列表視圖。請禁用或設置爲false並檢查您的代碼。 –

+0

就是這樣!萬分感謝! – cfihelp

0

無需使用布爾變量做如下。

if (commentsLayout.isShown()) { 
     commentsLayout.setVisibility(View.GONE); 
} else { 
     commentsLayout.setVisibility(View.VISIBLE); 
} 
相關問題