The onKeyDown method does not function. When i press the button the bitmap s does not move.
When it is done directly by putting j=j+5; inside canvas it works.
When did it directly in onkeydown j+5 then also it was’nt moving.
public class SmileyView extends SurfaceView implements SurfaceHolder.Callback {
public SmileyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = getHolder();
s= BitmapFactory.decodeResource(context.getResources(),R.drawable.smiley);
holder.addCallback(this);
sd=context.getResources().getDrawable(R.drawable.lander_plain);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
return rv.dokey();
}
private int i=100;private int j=0;
private Bitmap s;private SurfaceHolder holder;private RenderView rv ;
boolean grun=true;long t=0;private boolean key=false;private Drawable sd;volatile private int f=0;
public void resume()
{
rv=new RenderView();
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
grun=true;
if(rv!=null)
rv.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
try {
grun =false;
rv.join();
rv=null;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class RenderView extends Thread {
RenderView(){
super();
}
@Override
public void run()
{
SurfaceHolder h=holder;
while(grun)
{
Canvas ca=null;
try{ca = h.lockCanvas(null);
synchronized (h) {
dodraw(ca);
}
}
finally
{
if(ca!=null)
h.unlockCanvasAndPost(ca);
}
}
}
public void dodraw(Canvas canvas)
{ canvas.drawColor(Color.BLACK);
canvas.drawBitmap(s, j, j, null);
sd.setBounds(10, 10, 230, 180);
sd.draw(canvas);
key =false;
canvas.restore();
}
boolean dokey()
{
j=j+5;
return true;
}
}
}
The view has to have focus in order to accept key events, and besides forcing focusable on the element, theres no good way to make your SmileyView take focus. Instead, Override onKeyDown in your activity to pass through the key event, if this surfaceview is the only thing on the screen: