获取View的有效屏幕大小

在编写游戏时,需要针对不同屏幕的分辨率来控制显示图标的大小,针对继承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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值