java - 安卓 : Change background color of table rows when it is clicked

标签 java android tablelayout

在我的 Android 应用程序中,有一个在运行时加载的表格布局。我为表行设置了 OnClickListener。

tr.setClickable(true);
tr.setOnClickListener(trOnClickListener);

我需要在单击表行时更改其背景颜色。这是我的 onClick 方法。

private OnClickListener trOnClickListener = new OnClickListener() {
    public void onClick(View v) {

        TableRow tablerow = (TableRow)v;

        tablerow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.ab_stacked_solid_whiteaction));

    }
};

当我单击表格行时,它会更改背景颜色。当我单击另一行时,它也会更改其背景颜色。但我想要的是, 一次只能更改一行的背景颜色。

我怎样才能做到这一点?如有任何建议,我们将不胜感激。

提前致谢

最佳答案

在drawable文件夹中创建XML并将其设置为bg

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

    <item android:drawable="@drawable/cell_shape_in_white" android:state_pressed="true"/>
    <item android:drawable="@drawable/cell_shape_in_grey"/>

</selector>

或者

 <selector xmlns:android="http://schemas.android.com/apk/res/android">


    <item android:drawable="@drawable/cell_shape_in_white" android:state_focused="true" android:state_pressed="false"/>
    <item android:drawable="@drawable/cell_shape_in_white" android:state_focused="true"/>
    <item android:drawable="@drawable/cell_shape_in_grey" android:state_focused="false"/>
    <item android:drawable="@drawable/cell_shape_in_grey"/>

</selector>

或者

引用链接How to change the background color of a TableRow when focused?

关于java - 安卓 : Change background color of table rows when it is clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995385/

相关文章:

java - 如何在 Java 的 Scanner 实用程序中将输入放在下一行

android - 警告 : can't open config file: C:/OpenSSL/openssl. cnf

java - TableRow 宽度不一致 - Android

java - 使用 tc 服务器设置 kerberos 的问题

java - 使用两个字符java多次分割字符串

java - RabbitMQ Spring 死信配置不起作用

android - 在android中按字母顺序获取联系人?

android - CollapsingToolbarLayout 无法转换为 android.support.v7.widget.Toolbar

c# - TableLayoutPanel:删除行

android - 表格行划分