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;
}
}
}
视图必须具有焦点才能接受关键事件,除了强制聚焦在元素上之外,没有好方法可以让您的 SmileyView 获得焦点。相反,如果此图面视图是屏幕上的唯一内容,请在活动中重写 onKeyDown 以传递键事件:
public class MyActivity extends Activity {
private SmileyView mSmileyView
@Override
protected boolean onKeyDown(int keyCode, KeyEvent event) {
return mSmileyView.onKeyDown(keyCode, event);
}
}
您是否尝试调试?j 应同步。您可以从一个线程编辑它并在渲染线程中使用