zoukankan      html  css  js  c++  java
  • Android游戏开发教程之三:View类用法详解

      在上一节View类与SurfaceView类中,讲解了View类和SurfaceView类的区别。本节将详解View类的用法,从View类开始着重的介绍Android图形显示基类的相关方法和注意点。

           View类常用方法

           自定义View的常用方法:

           onFinishInflate() 当View中所有的子控件均被映射成xml后触发

           onMeasure(int, int) 确定所有子元素的大小

           onLayout(boolean, int, int, int, int) 当View分配所有的子元素的大小和位置时触发

           onSizeChanged(int, int, int, int) 当view的大小发生变化时触发

           onDraw(Canvas) view渲染内容的细节

           onKeyDown(int, KeyEvent) 有按键按下后触发

           onKeyUp(int, KeyEvent) 有按键按下后弹起时触发

           onTrackballEvent(MotionEvent) 轨迹球事件

           onTouchEvent(MotionEvent) 触屏事件

           onFocusChanged(boolean, int, Rect) 当View获取或失去焦点时触发 

           onWindowFocusChanged(boolean) 当窗口包含的view获取或失去焦点时触发

           onAttachedToWindow() 当view被附着到一个窗口时触发

           onDetachedFromWindow() 当view离开附着的窗口时触发,Android123提示该方法和  onAttachedToWindow() 是相反的。

           onWindowVisibilityChanged(int) 当窗口中包含的可见的view发生变化时触发

            以上是View实现的一些基本接口的回调方法。

           View类方法的重载

           一般我们需要处理画布的显示时,重写onDraw(Canvas)用的的是最多的:

    Java代码
    1.  @Override  
    2.   protected void onDraw(Canvas canvas) {   
    3.    //这里我们直接使用canvas对象处理当前的画布,比如说使用Paint来选择要填充的颜色   
    4.   
    5.   Paint paintBackground = new Paint();   
    6.   paintBackground.setColor(getResources().getColor(R.color.xxx));  //从Res中找到名为xxx的color颜色定义   
    7.   canvas.drawRect(00, getWidth(), getHeight(), paintBackground); //设置当前画布的背景颜色为paintBackground中定义的颜色,以0,0作为为起点,以当前画布的宽度和高度为重点即整块画布来填充。  具体的后面会讲,在Canvas中我们可以实现画路径,图形,区域,线。而Paint作为绘画方式的对象可以设置颜色,大小,甚至字体的类型等等。   
    8. }  

           当然还有就是处理窗口还原状态问题(一般用于横竖屏切换),除了在Activity中可以调用外,开发游戏时我们尽量在View中使用如下代码:

    Java代码
    1. @Override  
    2.    protected Parcelable onSaveInstanceState() {    
    3.       Parcelable p = super.onSaveInstanceState();   
    4.       Bundle bundle = new Bundle();   
    5.       bundle.putInt("x", pX);   
    6.       bundle.putInt("y", pY);   
    7.       bundle.putParcelable("android_state", p);   
    8.       return bundle;   
    9.    }   
    10.    @Override  
    11.    protected void onRestoreInstanceState(Parcelable state) {    
    12.       Bundle bundle = (Bundle) state;   
    13.       dosomething(bundle.getInt("x"), bundle.getInt("y")); //获取刚才存储的x和y信息   
    14.       super.onRestoreInstanceState(bundle.getParcelable("android_state"));   
    15.       return;   
    16.    }  

           在View中如果需要强制调用绘制方法onDraw,可以使用invalidate()方法,它有很多重载版本,同时在线程中的postInvailidate()方法在后面的教程中会讲到。

    本文转自:http://www.jizhuomi.com/android/game/49.html

  • 相关阅读:
    js截取字符串区分汉字字母代码
    List 去处自定义重复对象方法
    63. Unique Paths II
    62. Unique Paths
    388. Longest Absolute File Path
    41. First Missing Positive
    140. Word Break II
    139. Word Break
    239. Sliding Window Maximum
    5. Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/daichangya/p/12959945.html
Copyright © 2011-2022 走看看