This is my layout file
<RelativeLayout 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"
tools:context=".MainActivity" >
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" />
<!-- will add other views later -->
</RelativeLayout>
This is my custom view
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MyView extends View implements View.OnTouchListener {
...
@Override
protected void onDraw(Canvas canvas) {
….//draw some shapes
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
float xTouch = event.getX();
float yTouch = event.getY();
String str = "(" + xTouch + "," + yTouch + ")";
System.out.println(str);
Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
}
return true;
}
}
This is main activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View myView = new MyView(this, data);
FrameLayout container = (FrameLayout) findViewById(R.id.container);
container.addView(myView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PROBLEM
The app is not registering my touch events for custom view. The view displays all the contents of onDraw
, but when I click, onTouch is not registering. I try putting a break point at the if
in onTouch, but it's never reached.
it could be that you are not registering the onTouchListener to the view in a constructor, im not really sure but here onTouchEvent() is a method you override like onDraw for a view, maybe that would suit you better
@Override
public boolean onTouchEvent (MotionEvent event){
return true;
}