在相对布局上触摸事件时改变背景颜色

3
我正在使用以下代码。
  <RelativeLayout
            android:layout_width="310dp"
            android:layout_height="70dp"
            android:layout_below="@+id/UIReportView"
            android:layout_marginLeft="4dp"
            android:layout_marginTop="2dp"
            android:background="@drawable/small_corners" >

小圆角

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/UINoCorners"
    android:shape="rectangle">
    <corners android:radius="10dp"/>
    <padding android:left="10dp" 
             android:right="10dp" 
             android:top="5dp" 
             android:bottom="5dp"/>
    <solid android:color="#FFFFFF"/>

    </shape>

现在,它显示为白色条。我希望每当我点击这个相对布局时,它的颜色会改变成我设置的颜色。

 report = (RelativeLayout) findViewById(R.id.UIMainReportViewTimely);


       report .setOnClickListener(new View.OnClickListener() 
       {
        @Override
        public void onClick(View v) 
        {
// My Code
        }
       });

我该在这里做什么?report.onTouchEvent是什么?

我如何改变背景的颜色。

最好的问候

3个回答

4
创建一个新的可绘制对象,用于设置新的背景,在setOnclickListener方法中添加以下代码: report.setBackgroundDrawable(R.drawable.newbackground_small_corners); 或者
report.setBackgroundColor(Color.parseColor("#00000000"));

尝试了使用不同的颜色,但它只会变成黑色,而不是我想要的颜色。 - Muhammad Umar

3
您可以使用以下内容:
    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <stroke android:width="1dp" android:color="#999999" />
            <padding android:left="10dp" android:top="3dp" android:right="10dp"
                android:bottom="3dp" />
            <corners android:radius="7dp" android:bottomRightRadius="7dp"
                android:bottomLeftRadius="7dp" android:topLeftRadius="0dp"
                android:topRightRadius="0dp" />

            <gradient android:startColor="#449def" android:endColor="#2f6699"
                android:angle="270" />


        </shape>
    </item>
<item>
<shape>
    <corners android:radius="10dp"/>
    <padding android:left="10dp" 
             android:right="10dp" 
             android:top="5dp" 
             android:bottom="5dp"/>
    <solid android:color="#FFFFFF"/>
    </shape>
    </item>
</selector>
</shape>

0
我建议使用onTouch()方法并检查触摸坐标是否在相对布局范围内。如果是,则只需使用setBackgroundColor()设置背景色。

fullReport.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { report.setBackgroundColor(R.drawable.touchbackground_corners); return false; } }); 我这样做了,但当我点击它时,它只会变黑并调用已定义的onclickListener。 - Muhammad Umar

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