2014-07-14 26 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

相关问题