Here I have created and example of Touch Listener Image. In this example a image can pull left, right, up and down easily. It can be used to shift your mobile app icon left and right. For this in below code I have used MotionEvent() method. Below example will described you how to make Touch Listener image.
public class MainActivity extends Activity implements View.OnTouchListener {
Ourview v;
Bitmap bm;
float x,y;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new Ourview(this);
v.setOnTouchListener(this);
bm = BitmapFactory.decodeResource(getResources(), R.drawable.cross);
x=0;y=0;
setContentView(v);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
@Override
protected void onResume() {
super.onResume();
v.resume();
}
class Ourview extends SurfaceView implements Runnable {
Thread th = null;
SurfaceHolder holder;
boolean var = false;
public Ourview(Context context) {
super(context);
holder = getHolder();
}
@Override
public void run() {
while (var = true) {
// do stuff
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 250, 150, 20);//rgb values
c.drawBitmap(bm, x -(bm.getWidth()/2), y -(bm.getHeight()/2), null );
holder.unlockCanvasAndPost(c);
}
}
public void pause() {
var = false;
while (true) {
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
th = null;
}
public void resume() {
var = true;
th = new Thread(this);
th.start();
}
}
@Override
public boolean onTouch(View v, MotionEvent me) {
x=me.getX();//ontouch listener
y=me.getY();
return true;
}
}
0 Comment(s)