2014-02-05 136 views
2

我有一個表格行有多個數據。當單擊一行時,該特定行將以深灰色突出顯示。但是當我點擊下一行時,被點擊的行突出顯示,但前一行仍然突出顯示。我如何禁用上一行的高亮顯示。我嘗試了很多技巧,但這不起作用。突出顯示當表格行點擊並禁用下一行點擊

這是我的示例代碼。

tableRow.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      v.setBackgroundColor(Color.DKGRAY); 

} 

我已經以編程方式創建了佈局。我沒有使用XML。

在此先感謝。

+0

看到我的新的更新ü只是需要更多的'State'加入到'StateListDrawable'爲每U [R要求 –

回答

3

如果你想用股票上點擊亮點像你這樣一個通用的ListView得到,你要設置的每個行的背景是

android:background="@drawable/selector" 

下面是一個例子:

<TableRow 
    android:id="@+id/tableRow1" 
    android:layout_width="wrap_content" 
    android:layout_height="0dp" 
    android:layout_weight="1" 
    android:padding="5dip" 
    android:background="@drawable/selector"> 

這是selector.xmlres\drawable文件夾

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 
<item android:state_focused="true" 
     android:state_pressed="true" 
     android:drawable="@color/blue></item> 
<item android:state_focused="true" 
     android:state_pressed="false" 
     android:drawable="@color/custom"></item> 
<item 
     android:state_focused="false" 
     android:state_pressed="true" 
     android:drawable="@color/gray" /> 


<item android:drawable="@color/white"></item> 

</selector> 

更新:創建StateListDrawable編程像下面並設置爲BackgroundTableRow

Drawable d1=activity.getResources().getDrawable(R.drawable.gradient_bg_hover); 

    GradientDrawable g = new GradientDrawable(Orientation.TOP_BOTTOM, 
      new int[] { Color.DKGRAY});  
g.setGradientType(GradientDrawable.LINEAR_GRADIENT); 

      StateListDrawable states = new StateListDrawable(); 
      states.addState(new int[] {android.R.attr.state_pressed,-android.R.attr.state_selected},d1); 
      states.addState(new int[] {-android.R.attr.state_focused},g); 

      table_row.setBackgroundDrawable(states); 

這是res\drawable文件夾gradient_bg_hover.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
<!-- Gradient BgColor for listrow Selected --> 
<gradient 
    android:startColor="#18d7e5" 
    android:centerColor="#16cedb" 
    android:endColor="#09adb9" 
    android:angle="270" /> 
</shape> 

UPDATE2:您可以添加更多StateStateListDrawable按您的要求。

  1. android:state_activated:時設置視圖或其父已被「激活」,這意味着用戶目前已經將其標記爲感興趣。

  2. android:state_active:StateListDrawable的狀態值。

  3. android:state_enabled:啓用視圖時設置。

  4. android:state_focused:當視圖具有輸入焦點時設置的StateListDrawable的狀態值。

  5. android:state_pressed:當用戶在視圖中按下時設置。

  6. android:state_selected:噹噹前選擇視圖(或其父項之一)時設置。

更多有關StateListDrawable

+0

我已經創建的佈局編程。我沒有使用XML。 – Suniel

+0

@Suniel查看我的更新 –

+0

在任何情況下,它只會突出顯示最後一行。 – Suniel