单击表行并在单击下一行时禁用时突出显示

时间:2014-02-05 09:41:10

标签: android tablerow

我有一个包含多个数据的表格行。单击一行时,该特定行以深灰色突出显示。但是当我单击下一行时,单击的行会突出显示,但前一行仍然会突出显示。如何禁用上一行的突出显示。我尝试了许多技巧,但那不起作用。

这是我的示例代码。

tableRow.setOnClickListener(new View.OnClickListener() {

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

}

我已经以编程方式创建了布局。我没有使用XML。

提前致谢。

1 个答案:

答案 0 :(得分: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.xml文件夹中的res\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,如下所示,并将Background设置为TableRow

 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);

这是gradient_bg_hover.xml文件夹中的res\drawable

 <?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 :您可以根据自己的要求向State添加更多StateListDrawable

  1. android:state_activated:在视图或其父级已被“激活”时设置,表示用户当前已将其标记为感兴趣。

  2. android:state_active: StateListDrawable的州值。

  3. android:state_enabled:在启用视图时设置。

  4. android:state_focused: StateListDrawable的状态值,在视图具有输入焦点时设置。

  5. 当用户在视图中按下时,设置
  6. android:state_pressed:

  7. 当前选择了一个视图(或其中一个父视图)时设置
  8. android:state_selected:

  9. 有关StateListDrawable

    的更多信息
相关问题