如何更改焦点视图的背景颜色

6
我想改变焦点下视图的颜色;在我的情况下是一行表格。
这是我当前的代码,但它不起作用。
            r.setOnTouchListener(new OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1) {
                {               {
                    arg0.setBackgroundColor(Color.LTGRAY);
                    r.setFocusableInTouchMode(true);
                }
            return false;
        }});

这段代码实际上在发生什么? - ingsaurabh
抱歉..看了编辑后的那个..在这样做后,整行在我点击它后都会改变颜色..而在选择多行时每一行都保持着这种颜色..我尝试使用isFocussed()在if条件中..但没起作用。 - ngesh
我不确定,但据我所知,tablerow在焦点上颜色不会改变。您可以使用ListView来实现。 - Jaydeep Khamar
但你确定listView可以替代tablerow的作用吗? - ngesh
2个回答

4
你可以使用XML drawable,
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList。 像这样创建一个XML:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

你需要为此添加背景图片。

好的,让我看看这是否可行。上面的 XML 文件应该手动粘贴到 res 目录中,对吗? - ngesh
如果答案对您有用,请接受它,或回复您得到的输出,这样如果这个答案不起作用,我们也可以以其他方式帮助您:) - Jaydeep Khamar
周围的每个人都建议同样的答案...但是这是一个有点困难的过程,因为你需要清楚地了解Android文件系统的信息...这不仅仅是编码...而且我是一名新手,不是那么完美...还在努力中...如果我成功了,会让你知道的。 - ngesh

1

这里我为您提供一些示例... http://life-as-a-coder.com/_shared/background_state.rar

看一下我的main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:background="@drawable/item_background"
        android:clickable="true">
        <TextView
            android:text="Item 1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35dip"></TextView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:background="@drawable/item_background"
        android:clickable="true">
        <TextView
            android:text="Item 2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35dip"></TextView>
    </LinearLayout>
</LinearLayout>

我在这个例子中使用LinearLayout。我设置android:clickable="true"来激活点击状态... 这也可以用于ListView... 只需在自定义行项目上使用它... 对于我的糟糕的英语和语法,我感到抱歉。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接