onKeyDown 方法不起作用。当我按下按钮时,位图 s 不会移动。当它直接通过设置 j=j+5 来完成时;在画布里面它工作。什么时候直接在 onkeydown j+5 中进行的,然后它也没有移动。
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;
}
}
}