在编写游戏时,需要针对不同屏幕的分辨率来控制显示图标的大小,针对继承View的定制View 缺省的getWidth(),getHeight()为0,尝试如下方法:
1:在View的构造函数中,向根据View所在的Activity对象中的根FrameLayout获取屏幕大小
public BoardView(Context context,AttributeSet atts) {
super(context,atts);
Chessboard cb=(Chessboard)context;
int viewWidth=cb.getScreenwidth();
int viewHeight=cb.getScreenheight();
if(viewWidth==320&&viewHeight==480){
Log.i("BoardView screen", "3.2 Screen");
}else{
if(viewWidth>0){
iconSize=viewWidth/8;
}
}
}
对应ChessBoard继承BaseGameActivity
public class BaseGameActivity extends Activity {
private int screenwidth;
private int screenheight;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//not show title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//keep screen on
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//keep full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
FrameLayout root=(FrameLayout)getWindow().findViewById(Window.ID_ANDROID_CONTENT);
screenwidth=root.getWidth();
screenheight=root.getHeight();
}
public int getScreenwidth() {
return screenwidth;
}
public void setScreenwidth(int screenwidth) {
this.screenwidth = screenwidth;
}
public int getScreenheight() {
return screenheight;
}
public void setScreenheight(int screenheight) {
this.screenheight = screenheight;
}
}
但是很遗憾,获取不到对应的屏幕大小,该方法为从网上查到的,但是无效
2:通过onSizeChanged方法获取屏幕大小
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.i("BoardView execute", "onSizeChanged screen width"+w+" screen height:"+h);
if(w==320&&h==480){
Log.i("BoardView screen", "3.2 Screen");
}else{
if(w<h&&w>0){
iconSize=w/8;
}
if(w>h&&h>0){
iconSize=h/8;
}
}
}
该方法有效的,但是需要注意该方法的调用顺序
View的几个方法的优先级
Constructor >onSizeChanged>onDraw