在relativelayout上更改触摸事件的背景颜色

时间:2012-03-28 09:44:40

标签: java android eclipse

我正在使用以下代码。

  <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" >

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 个答案:

答案 0 :(得分:4)

使用新背景创建另一个drawable,并在setOnclickListener put

中创建

report.setBackgroundDrawable(R.drawable.newbackground_small_corners);

report.setBackgroundColor(Color.parseColor("#00000000"));

答案 1 :(得分: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>

答案 2 :(得分:0)

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

相关问题