Custom View, detect touch to toggle color

This example implement a custom view, it have only one function, toggle color if user touched.


Create MyView.java
package com.example.androidtouchview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

boolean touchOn;

public MyView(Context context) {
super(context);
init();
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

private void init() {
touchOn = false;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

@Override
protected void onDraw(Canvas canvas) {
if (touchOn) {
canvas.drawColor(Color.RED);
} else {
canvas.drawColor(Color.GRAY);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);

int action = event.getAction();

if(action == MotionEvent.ACTION_DOWN){
touchOn = !touchOn;
invalidate();
return true;
}

return false;
}

}

Modify /res/layout/activity_main.xml to include the custom view.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.androidtouchview.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<com.example.androidtouchview.MyView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_margin="10dp"/>
<com.example.androidtouchview.MyView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:layout_margin="10dp"/>

</LinearLayout>

</LinearLayout>

Keep using the auto generated MainActivity.java

You will be warned "MyView overrides onTouchEvent but not performClick" on onTouchEvent() method, read next post to fix it.