2014-07-14 27 views
0

我的目的是使選中的項目(從列表視圖)變得突出顯示。 和它的作品完美地使用下面的代碼:onItemClick列表視圖和一個循環內部案例

@Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int post, 
        long arg3) { 

       int itemPosition = post; 
       String itemValue = (String) lst_peers 
         .getItemAtPosition(itemPosition); 
       sendMessage(itemValue + " has been selected!"); 

       obOpponent = new Opponent(peerListID.get(itemPosition), 
         itemValue); 

       // turning off the discovery process if any 
       discTime = 0; 

       // set the item highlighted 
       lst_peers.setItemChecked(itemPosition, true); 
       arg1.setBackgroundColor(Color.YELLOW); 

      } 

但是,我的問題是 如何使項目恢復到正常狀態的顏色(未高亮顯示), 一旦用戶點擊其他項目?

我試圖把循環放在onItemClick方法中,但android崩潰!

+2

最好使用'Selector'並設置爲您的'ListItem'作爲背景...... –

+0

如果您使用的是自定義適配器,則應在適配器的getView()方法內部執行此操作。 –

+0

什麼時候getView()被執行了? @ShivamVerma – gumuruh

回答

1

回答1 - 最快:

嘗試一個小竅門:

定義一個全局視圖變量View TempView,並用它來你的View arg1存儲供以後(旁邊點擊)將其更改爲原始背景:

 @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int post, 
       long arg3) { 

      int itemPosition = post; 
      String itemValue = (String) lst_peers 
        .getItemAtPosition(itemPosition); 
      sendMessage(itemValue + " has been selected!"); 

      obOpponent = new Opponent(peerListID.get(itemPosition), 
        itemValue); 

      // turning off the discovery process if any 
      discTime = 0; 

      // set the item highlighted 
      lst_peers.setItemChecked(itemPosition, true); 
      if (!(tempView == null)) { 
        tempView.setBackgroundColor(YOUR_ORIGINAL_BACKGROUND); 
       } 
       tempView = arg1; 
       tempView.setBackgroundColor(Color.YELLOW); 


     } 

無論何時單擊,將顏色更改爲黃色,並且以前單擊的顏色都會返回到所需的原始顏色。

答案2 - 最好的一個 - 在你的XML選擇

,添加到您的列表視圖android:listSelector="@drawable/yourselector" > 這是您實現內部的ListView你的點擊事件,如下面的示例XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:state_enabled="true"> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
      android:startColor="#6018d7e5" 
      android:centerColor="#6016cedb" 
      android:endColor="#6009adb9" 
      android:angle="270" /> 
    </shape> 
    </item> 
    <item android:state_pressed="true"> 
     <!-- (...) 
    </item> 
    <item android:state_selected="true" android:state_pressed="false"> 
     <!-- (...) 
    </item> 

</selector> 
+0

很高興知道您的解決方案@PedroHawk ....也許您可以在其他話題中幫助我?在這裏:https://programmers.stackexchange.com/questions/247000/wifi-communication-between-two-device-without-intermediary-device或者在這裏:https://programmers.stackexchange.com/questions/249758/exximity -sdk替代品換機器人 – gumuruh

相關問題