Reputation: 3236
I have a RelativeLayout
I want to perform a touch event with out touching the screen want to give a Toast
message if its actually touched or not.Please throw I have tried with the below it seems not working
MotionEvent event = MotionEvent.obtain(downTime, eventTime, action,
x, y, pressure, size,
metaState, xPrecision, yPrecision,
deviceId, edgeFlags);
onTouchEvent(event);
Upvotes: 3
Views: 10338
Reputation: 1
Try This
Button btnTouch = (Button) findViewById(R.id.btn_touch);
btnTouch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
x++;
y++;
perFromTouch(x,y);
}
});
private void perFromTouch(float x, float y) {
// Obtain MotionEvent object
long initTime = android.os.SystemClock.uptimeMillis();
long eventTime = android.os.SystemClock.uptimeMillis() + 100;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
initTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
);
motionEvent.setSource(inputSource);
v.dispatchTouchEvent(motionEvent);
}
Upvotes: 0
Reputation: 947
You should not do that. If you indeed want to "touch" your view programatically, you should wrap whatever happens in your onTouch method in another function(without the MotionEvent parameter) and call that function, when you want to touch your view. Calling the onTouch without a real touch would get you negative stylepoints
@Override
boolean onTouch(View v, MotionEvent me) {
return action(me.getX(),me.getY());
}
boolean action(int x, int y) {
//do some stuff
}
void somewhereelse() {
//Perform touch action
action(0,0);
}
If you really want to 'dispatch' a touch event. You do it like this:
View v;
v.dispatchTouchEvent(MotionEvent.obtain(0,0,MotionEvent.ACTION_DOWN, 100,100,0.5f,5,0,1,1,0,0));
The values are pretty random. Only the deviceId=0 indicates that it is programatically dispatched Touch.
Upvotes: 7
Reputation: 19
Find your layout in activity
RelativeLayout layout=(RelativeLayout)findviewbyid(R.id.relativelayout);
layout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
//do your work
return false;
}
});
Upvotes: -1