2014-09-30 27 views
0

我有一個ListView與一組元素。當我點擊其中一個時,我想禁用所有其他人。如果再次點擊所選項目,所有其他項目都會再次啓用。如何在列表視圖中禁用所有元素(也是屏幕上當前不可見的元素)?

我嘗試了不同的建議解決方案,但沒有成功。我希望有一個人可以幫助我。

這是我的代碼:

//action to take when a presentation is selected 
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
     public void onItemClick(AdapterView<?> parent, final View view, 
      int position, long id) { 
     //disable the other items when one is selected 
     if(position!=selectedPresentation){ 
       for(int i=0;i<parent.getCount();i++){ 
        if(i!=position)//disable all the items except the select one 
         parent.getChildAt(i).setEnabled(false); 
       } 
       selectedPresentation=position; 

      }else if(selectedPresentation==position){ 
       //enable again all the items 
       for(int i=0;i<parent.getCount();i++){ 
        parent.getChildAt(i).setEnabled(true); 
       } 
       selectedPresentation=-1; 

      } 

凡selectedPresentation是一個全局變量存儲所選擇的項目。如果沒有選擇項目,它的值是-1。

謝謝你的幫助!

+0

嘗試的項目,以保持一個標誌isEnable在列表中的數據,並嘗試更改標誌值,無論是哪個點擊,並且在嘗試通知列表之後還要更改列表項值的其餘部分,並在基於標誌狀態的getView()中設置enable-disable。 – 2014-09-30 12:55:33

+0

就像一個巨大的無線電集團。 – danny117 2014-09-30 13:25:08

+0

問題是,當你滾動(使新元素出現)或添加一個新元素時,getView()在開始時被調用來創建列表 – 2014-09-30 13:55:14

回答

0

使您自己的ArrayAdapter的子類具有AreAllItemsEnabled()返回false,並且定義isEnabled(int position)以針對您要禁用的某個給定項返回false。

在您的自定義ArrayAdapter此改變的IsEnabled方法如下

@Override 
public boolean isEnabled(int position) { 
    return false; 
} 

其他選項

沒有實現onItemclickListener。這不會給你任何更新項目click。僅將onClick監聽器註冊到views

0

你可能會採用列表視圖中的另一個對象(Arraylist),它是在列表視圖中填充元素,然後點擊將相應的位置數據複製到您創建的新數組列表中,然後通知數據集,當您再次單擊時使用原始列表填充列表視圖將再次apear ....只要做這個詭計它可能會爲你工作

0

parent.getChildeAt()只適用於可見的項目。 你應該改變適配器的東西。
如果製作自定義適配器,那麼你可以做一些事情,如@ṁᾶƔƏňツ答案,但如果你使用默認適配器,你可以在將適配器傳遞給適配器之前更改適配器的數組列表。
把它布爾(在arraylist)和在項目上點擊true/false它爲所有項目。

0

我寫了這個解決方案,似乎它工作正常!

  listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        @Override 
      public void onItemClick(AdapterView<?> parent, final View view, 
       int position, long id) { 
      //disable the other items when one is selected 
         Toast.makeText(context, "onClick called",Toast.LENGTH_SHORT).show(); // this will flash up twice 

         if(position!=selectedPresentation){ 
         selectedPresentation=position; 
        for(int i=0;i<adapter.getCount();i++){ 
         if(i!=position)//disable all the items except the select one 
          adapter.isEnabled(i); 
        } 


       }else if(selectedPresentation==position){ 
        //enable again all the items 
        selectedPresentation=-1; 
        for(int i=0;i<adapter.getCount();i++){ 
         adapter.isEnabled(i); 
        } 


       } 

而在我的適配器,我寫道:

public boolean isEnabled(int position) { 
    if(selectedPresentation==-1 || selectedPresentation==position) 
     return true; 
    return false; 

現在我關心的是如何顯示在ListView爲禁用

相關問題