Thursday, July 18, 2013

Android: View + touch listener

  1. implements View.OnTouchListener
  2. add public boolean onTouch(View v, MotionEvent event) method
  3. view.setOnTouchListener(this);
  4. event.getX() or getY() to get position of touch
sample code:
public class SecondActivity extends Activity implements View.OnTouchListener{
MyCanvas c;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
c = (MyCanvas)this.findViewById(R.id.myCanvas1);
tv = (TextView)this.findViewById(R.id.textView1);
c.setOnTouchListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
public boolean onTouch(View v, MotionEvent event){
if(v ==c ){
tv.setText("touched: " + event.getX() + ", " + event.getY());
}
return false;
}
}

No comments: