我需要使用view.getWidth()
,但我不能,因为我还没有夸大视图。如何在使用view.getWidth()
之前对视图进行充气?
MainActivity
类:
public class MainActivity extends Activity {
GameView gv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_view);
LinearLayout surface = new LinearLayout(this);
surface = (LinearLayout)findViewById(R.id.surface);
gv= new GameView(this,surface);
surface.addView(gv);
}
GameView
类:
public class GameView extends SurfaceView implements Runnable {
private boolean isRunning=false;
private final long FPS=12;
int PART_SIZE=6;
private SurfaceHolder holder;
Thread snakethread;
Snake snake;
Arena a;
Brick food;
LinearLayout view;
Bitmap arena;
public GameView(Context context,LinearLayout view) {
super(context);
this.view=view;
arena = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
this.a=new Arena();
snakethread=new Thread(this);
holder= getHolder();
this.setBackgroundColor(Color.TRANSPARENT);
this.setZOrderOnTop(true);
getHolder().setFormat(PixelFormat.TRANSPARENT);
holder.addCallback(new SurfaceHolder.Callback(){
@Override
public void surfaceCreated(SurfaceHolder arg0) {
setRunning(true);
snakethread.start();
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,int arg3) {
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
setRunning(false);
while(true){
try {
snakethread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
snake=new Snake(20, 50, "RIGHT",PART_SIZE);
}
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
Canvas c = null;
try{
c=this.getHolder().lockCanvas();
synchronized (this.getHolder()) {
ArenaDraw(c);
}
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
while(isRunning){
c=null;
startTime=System.currentTimeMillis();
try{
c=this.getHolder().lockCanvas();
synchronized (this.getHolder()) {
Paint p=new Paint();
snakeDraw(c);
}
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
您可以使用ViewTreeObserver
:
final ViewTreeObserver observer = surface.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
// do what you need to do, getWidth() is now valid
surface.getWidth();
return false; // will not draw this initial frame
}
});
请注意,仅对视图进行充气是不够的。在getWidth()变为有效之前,您的视图需要通过inflate-measure-layout生命周期。