简体   繁体   中英

Changing background color on touchevent on relative layout

i am using following code.

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

Now , it shows a white bar. I want that, whenever i click on this relative layout its color should change, set by me.

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


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

What should i do here? report.onTouchEvent?

And how can i change the color of background.

Best Regards

Create another drawable with the new background, and in your setOnclickListener put

report.setBackgroundDrawable(R.drawable.newbackground_small_corners);

or

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

you can use this:-

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

I'd rather suggest to use the onTouch() method and check whether the touched coordinates are within the bounds of your relative layout. If yes, then just set background using setBackgroundColor() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM