日积月累第三周第四天。又是忙碌的一天,昨天看了两集老罗的Android 视频教程,感觉讲的很基础。继续坚持一天一集视频。今天上班接触了一下Android 的LayoutParams今天加以整理和梳理。

先查看一下API 中是如何介绍的,以搜索太多了。就挑一个ViewGroup.LayoutParams 看一下吧

http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.

The base LayoutParams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of:

  • FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)
  • WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding)
  • an exact number
There are subclasses of LayoutParams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of LayoutParams which adds an X and Y value.

Developer Guides

For more information about creating user interface layouts, read the XML Layouts developer guide.

我在这里看了一篇别人博客对于LayoutParams 的解释,我觉的很到位,所以就继续拿来主义。

其实这个LayoutParams类是用于child view(子视图) 向 parent view(父视图)传达自己的意愿的一个东西(孩子想变成什么样向其父亲说明)其实子视图父视图可以简单理解成
一个LinearLayout 和 这个LinearLayout里边一个 TextView 的关系 TextView 就算LinearLayout的子视图 child view 。需要注意的是LayoutParams只是ViewGroup的一个内部类这里边这个也就是ViewGroup里边这个LayoutParams类是 base class 基类实际上每个不同的ViewGroup都有自己的LayoutParams子类
比如LinearLayout 也有自己的 LayoutParams 大家打开源码看几眼就知道了
myeclipse 怎么查看源码 请看http://byandby.iteye.com/blog/814277
下边来个例子


 

Java代码 :
  1.       //创建一个线性布局   
  2.        private LinearLayout mLayout;      
  3.        mLayout = (LinearLayout) findViewById(R.id.layout);      
  4.       //现在我要往mLayout里边添加一个TextView    
  5.      //你可能会想直接在布局文件里边配置不就O 了 那是 但是这里为了说明问题我们用代码实现   
  6.       TextView textView = new TextView(Activity01.this);      
  7.            textView.setText("Text View " );   
  8.            //这里请不要困惑这里是设置 这个textView的布局 FILL_PARENT WRAP_CONTENT 和在xml文件里边设置是一样的如   
  9.     
  10. //在xml里边怎么配置高宽大家都会的。   
  11.   //第一个参数为宽的设置,第二个参数为高的设置。   
  12.            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(      
  13.                    LinearLayout.LayoutParams.FILL_PARENT,      
  14.                    LinearLayout.LayoutParams.WRAP_CONTENT      
  15.            );      
  16.            //调用addView()方法增加一个TextView到线性布局中   
  17.            mLayout.addView(textView, p);      
  18.           //比较简单的一个例子  


如果还不能理解下边在来一段直白的说明:
LayoutParams继承于Android.View.ViewGroup.LayoutParams.
LayoutParams相当于一个Layout的信息包,它封装了Layout的位置、高、宽等信息。假设在屏幕上一块区域是由一个Layout占领的,如果将一个View添加到一个Layout中,最好告诉Layout用户期望的布局方式,也就是将一个认可的layoutParams传递进去。
可以这样去形容LayoutParams,在象棋的棋盘上,每个棋子都占据一个位置,也就是每个棋子都有一个位置的信息,如这个棋子在4行4列,这里的“4行4列”就是棋子的LayoutParams。
但LayoutParams类也只是简单的描述了宽高,宽和高都可以设置成三种值:
1,一个确定的值;
2,FILL_PARENT,即填满(和父容器一样大小);
3,WRAP_CONTENT,即包裹住组件就好。

关于setLayoutParams报错

 

  在继承BaseAdapter的时候,用getView返回View的时候,用代码控制布局,需要用到View.setLayoutParams,但是报错了,报的是类型转换错误,经过研究,发现,这里不能使用ViewGroup.LayoutParams而必须使用对应父View的LayoutParams类型。如:某View被LinearLayout包含,则该View的setLayoutParams参数类型必须是LinearLayout.LayoutParams。原因在于LinearLayout(或其他继承自ViewGroup的layout,如:RelativeLayout)在进行递归布局的时候,LinearLayout会获取子View的LayoutParams,并强制转换成LinearLayout.LayoutParams,如

1 LinearLayout.LayoutParams lp  =  (LinearLayout.LayoutParams) child.getLayoutParams();

或者是如下定义:

1 LayoutParams lp  =  (LayoutParams) child.getLayoutParams();

以转换成内部类型LinearLayout.LayoutParams。

 

自己测试运行的时候报空指针,原因为child.getLayoutParams();这里没有获得到子控件所在的布局,查看代码发现parent.addView(child);应该写在上面,之后child才能getLayoutParams();



点击PopupWindow 外部区域消失
//view 是自定义的点击PopupWindow 样式
pop = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                pop.setBackgroundDrawable(new BitmapDrawable());
                pop.setOutsideTouchable(true);
pop = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                pop.setBackgroundDrawable(new BitmapDrawable());
                pop.setOutsideTouchable(true);
上面两句位置不能颠倒,不然无效!(经本机测试 不知道别人如何)必须设置backgroundDrawable()


  WindowManager.LayoutParams 是 WindowManager 接口的嵌套类;继承于 ViewGroup.LayoutParams 。
         它的内容十分丰富。其实WindowManager.java的主要内容就是由这个类定义构成。下面来分析一下这个类:

         定义
         public static class WindowManager.LayoutParams extends ViewGroup.LayoutParams implements Parcelable

         继承关系
        java.lang.Object
        android.view.ViewGroup.LayoutParams
        android.view.WindowManager.LayoutParams

        继承来的属性与常量
        从ViewManager.LayoutParams 继承来的属性:
        android:layout_height
        Specifies the basic height of the view.
        android:layout_width
        Specifies the basic width of the view.

        从ViewManager.LayoutParams继承的常量:
        FILL_PARENT
        WRAP_CONTENT
        MATCH_PARENT

        两个变量:
        width
        height

        属性及可用的常量定义

       1. public int x;
       如果忽略gravity属性,那么它表示窗口的绝对X位置。
       什么是gravity属性呢?简单地说,就是窗口如何停靠。
       当设置了 Gravity.LEFT 或 Gravity.RIGHT 之后,x值就表示到特定边的距离。

       2. public int y;
       如果忽略gravity属性,那么它表示窗口的绝对Y位置。
       当设置了 Gravity.TOP 或 Gravity.BOTTOM 之后,y值就表示到特定边的距离。

       3. public float horizontalWeight;
       public float verticalWeight;
       在纵/横向上,为关联的view预留了多少扩展空间(像素)。如果是0,那么此view不能被拉伸。
       其他情况下,扩展空间(像素)将被widget所均分。

       4. public int type;
        窗口类型。

        有3种主要类型:

        Applicationwindows:
        取值在 FIRST_APPLICATION_WINDOW 和 LAST_APPLICATION_WINDOW 之间。
        是通常的、顶层的应用程序窗口。必须将 token 设置成 activity 的 token 。

       Sub_windows:
        取值在 FIRST_SUB_WINDOW 和 LAST_SUB_WINDOW 之间。
        与顶层窗口相关联,token 必须设置为它所附着的宿主窗口的 token。

        Systemwindows:
        取值在 FIRST_SYSTEM_WINDOW 和 LAST_SYSTEM_WINDOW 之间。
        用于特定的系统功能。它不能用于应用程序,使用时需要特殊权限。

        下面定义了 type 的取值:

//应用程序窗口。
public static final int FIRST_APPLICATION_WINDOW = 1; 


//所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。 
public static final int TYPE_BASE_APPLICATION =1;


//普通应用功能程序窗口。token必须设置为Activity的token,以指出该窗口属谁。
public static final int TYPE_APPLICATION = 2;


//用于应用程序启动时所显示的窗口。应用本身不要使用这种类型。
//它用于让系统显示些信息,直到应用程序可以开启自己的窗口。 
public static final int TYPE_APPLICATION_STARTING = 3; 


//应用程序窗口结束。
public static final int LAST_APPLICATION_WINDOW = 99;


//子窗口。子窗口的Z序和坐标空间都依赖于他们的宿主窗口。
public static final int FIRST_SUB_WINDOW = 1000;


//面板窗口,显示于宿主窗口上层。
public static final int TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW;


//媒体窗口,例如视频。显示于宿主窗口下层。
public static final int TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1;


//应用程序窗口的子面板。显示于所有面板窗口的上层。(GUI的一般规律,越“子”越靠上)
public static final int TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW +2;


//对话框。类似于面板窗口,绘制类似于顶层窗口,而不是宿主的子窗口。
public static final int TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW +3;


//媒体信息。显示在媒体层和程序窗口之间,需要实现透明(半透明)效果。(例如显示字幕)
public static final int TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW +4;


//子窗口结束。( End of types of sub-windows )
public static final int LAST_SUB_WINDOW = 1999;


//系统窗口。非应用程序创建。
public static final int FIRST_SYSTEM_WINDOW = 2000;


//状态栏。只能有一个状态栏;它位于屏幕顶端,其他窗口都位于它下方。
public static final int TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW;


//搜索栏。只能有一个搜索栏;它位于屏幕上方。
public static final int TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1;


//电话窗口。它用于电话交互(特别是呼入)。它置于所有应用程序之上,状态栏之下。
public static final int TYPE_PHONE = FIRST_SYSTEM_WINDOW+2;


//系统提示。它总是出现在应用程序窗口之上。
public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW +3;


//锁屏窗口。
public static final int TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW +4;


//信息窗口。用于显示toast。
public static final int TYPE_TOAST = FIRST_SYSTEM_WINDOW +5;


//系统顶层窗口。显示在其他一切内容之上。此窗口不能获得输入焦点,否则影响锁屏。
public static final int TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW +6;


//电话优先,当锁屏时显示。此窗口不能获得输入焦点,否则影响锁屏。
public static final int TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW +7;


//系统对话框。(例如音量调节框)。
public static final int TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW +8;


//锁屏时显示的对话框。
public static final int TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW +9;


//系统内部错误提示,显示于所有内容之上。
public static final int TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW +10;


//内部输入法窗口,显示于普通UI之上。应用程序可重新布局以免被此窗口覆盖。
public static final int TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW +11;


//内部输入法对话框,显示于当前输入法窗口之上。
public static final int TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW +12;


//墙纸窗口。
public static final int TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW +13;


//状态栏的滑动面板。
public static final int TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW +14;


//系统窗口结束。
public static final int LAST_SYSTEM_WINDOW = 2999;

 5. public int memoryType;
       指出窗口所使用的内存缓冲类型。默认为 NORMAL 。

       下面定义了 memoryType 的取值:

       窗口缓冲位于主内存。
       public static final int MEMORY_TYPE_NORMAL = 0;
       窗口缓冲位于可以被DMA访问,或者硬件加速的内存区域。
       public static final int MEMORY_TYPE_HARDWARE = 1;
       窗口缓冲位于可被图形加速器访问的区域。
       public static final int MEMORY_TYPE_GPU = 2;
       窗口缓冲不拥有自己的缓冲区,不能被锁定。缓冲区由本地方法提供。
       public static final int MEMORY_TYPE_PUSH_BUFFERS = 3;

       6.  public int flags;
       行为选项/旗标,默认为 none .下面定义了 flags 的取值:

//窗口之后的内容变暗。
public static final int FLAG_DIM_BEHIND = 0x00000002;


//窗口之后的内容变模糊。
public static final int FLAG_BLUR_BEHIND = 0x00000004; 


不许获得焦点。
不能获得按键输入焦点,所以不能向它发送按键或按钮事件。那些时间将发送给它后面的可以获得焦点的窗口。此选项还会设置FLAG_NOT_TOUCH_MODAL选项。设置此选项,意味着窗口不能与软输入法进行交互,所以它的Z序独立于任何活动的输入法(换句话说,它可以全屏显示,如果需要的话,可覆盖输入法窗口)。要修改这一行为,可参考FLAG_ALT_FOCUSALBE_IM选项。
public static final int FLAG_NOT_FOCUSABLE = 0x00000008;


//不接受触摸屏事件。
public static final int FLAG_NOT_TOUCHABLE = 0x00000010;


当窗口可以获得焦点(没有设置 FLAG_NOT_FOCUSALBE 选项)时,仍然将窗口范围之外的点设备事件(鼠标、触摸屏)发送给后面的窗口处理。否则它将独占所有的点设备事件,而不管它们是不是发生在窗口范围内。
public static final int FLAG_NOT_TOUCH_MODAL = 0x00000020;


如果设置了这个标志,当设备休眠时,点击触摸屏,设备将收到这个第一触摸事件。
通常第一触摸事件被系统所消耗,用户不会看到他们点击屏幕有什么反应。
public static final int FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040;


当此窗口为用户可见时,保持设备常开,并保持亮度不变。
public static final int FLAG_KEEP_SCREEN_ON = 0x00000080;


窗口占满整个屏幕,忽略周围的装饰边框(例如状态栏)。此窗口需考虑到装饰边框的内容。
public static final int FLAG_LAYOUT_IN_SCREEN =0x00000100;


允许窗口扩展到屏幕之外。
public static final int FLAG_LAYOUT_NO_LIMITS =0x00000200;


窗口显示时,隐藏所有的屏幕装饰(例如状态条)。使窗口占用整个显示区域。
public static final int FLAG_FULLSCREEN = 0x00000400;


此选项将覆盖FLAG_FULLSCREEN选项,并强制屏幕装饰(如状态条)弹出。
public static final int FLAG_FORCE_NOT_FULLSCREEN =0x00000800;


抖动。指 对半透明的显示方法。又称“点透”。图形处理较差的设备往往用“点透”替代Alpha混合。
public static final int FLAG_DITHER = 0x00001000;


//不允许屏幕截图。
public static final int FLAG_SECURE = 0x00002000;


//一种特殊模式,布局参数用于指示显示比例。
public static final int FLAG_SCALED = 0x00004000;


//当屏幕有可能贴着脸时,这一选项可防止面颊对屏幕造成误操作。
public static final int FLAG_IGNORE_CHEEK_PRESSES = 0x00008000;


//当请求布局时,你的窗口可能出现在状态栏的上面或下面,从而造成遮挡。当设置这一选项后,窗口管理器将确保窗口内容不会被装饰条(状态栏)盖住。
public static final int FLAG_LAYOUT_INSET_DECOR = 0x00010000;


//反转FLAG_NOT_FOCUSABLE选项。
//如果同时设置了FLAG_NOT_FOCUSABLE选项和本选项,窗口将能够与输入法交互,允许输入法窗口覆盖;
如果FLAG_NOT_FOCUSABLE没有设置而设置了本选项,窗口不能与输入法交互,可以覆盖输入法窗口。
public static final int FLAG_ALT_FOCUSABLE_IM = 0x00020000;


//如果你设置了FLAG_NOT_TOUCH_MODAL,那么当触屏事件发生在窗口之外事,可以通过设置此标志接收到一个MotionEvent.ACTION_OUTSIDE事件。注意,你不会收到完整的down/move/up事件,只有第一次down事件时可以收到ACTION_OUTSIDE。
public static final int FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000;


//当屏幕锁定时,窗口可以被看到。这使得应用程序窗口优先于锁屏界面。可配合FLAG_KEEP_SCREEN_ON选项点亮屏幕并直接显示在锁屏界面之前。可使用FLAG_DISMISS_KEYGUARD选项直接解除非加锁的锁屏状态。此选项只用于最顶层的全屏幕窗口。
public static final int FLAG_SHOW_WHEN_LOCKED = 0x00080000;


//请求系统墙纸显示在你的窗口后面。窗口必须是半透明的。
public static final int FLAG_SHOW_WALLPAPER = 0x00100000;


//窗口一旦显示出来,系统将点亮屏幕,正如用户唤醒设备那样。
public static final int FLAG_TURN_SCREEN_ON = 0x00200000;


//解除锁屏。只有锁屏界面不是加密的才能解锁。如果锁屏界面是加密的,那么用户解锁之后才能看到此窗口,除非设置了FLAG_SHOW_WHEN_LOCKED选项。
public static final int FLAG_DISMISS_KEYGUARD = 0x00400000;


//锁屏界面淡出时,继续运行它的动画。
public static final int FLAG_KEEP_SURFACE_WHILE_ANIMATING =0x10000000;


//以原始尺寸显示窗口。用于在兼容模式下运行程序。
public static final int FLAG_COMPATIBLE_WINDOW = 0x20000000;


//用于系统对话框。设置此选项的窗口将无条件获得焦点。
public static final int FLAG_SYSTEM_ERROR = 0x40000000;

      7. public int softInputMode;
       软输入法模式选项:以下选项与 softInputMode 有关:


//软输入区域是否可见。
public static final int SOFT_INPUT_MASK_STATE = 0x0f;


//未指定状态。
public static final int SOFT_INPUT_STATE_UNSPECIFIED = 0;


//不要修改软输入法区域的状态。
public static final int SOFT_INPUT_STATE_UNCHANGED = 1;


//隐藏输入法区域(当用户进入窗口时)。
public static final int SOFT_INPUT_STATE_HIDDEN = 2;


//当窗口获得焦点时,隐藏输入法区域。
public static final int SOFT_INPUT_STATE_ALWAYS_HIDDEN = 3;


//显示输入法区域(当用户进入窗口时)。
public static final int SOFT_INPUT_STATE_VISIBLE = 4;


//当窗口获得焦点时,显示输入法区域。
public static final int SOFT_INPUT_STATE_ALWAYS_VISIBLE = 5;


//窗口应当主动调整,以适应软输入窗口。
public static final int SOFT_INPUT_MASK_ADJUST = 0xf0;


//未指定状态,系统将根据窗口内容尝试选择一个输入法样式。
public static final int SOFT_INPUT_ADJUST_UNSPECIFIED = 0x00;


//当输入法显示时,允许窗口重新计算尺寸,使内容不被输入法所覆盖。
//不可与SOFT_INPUT_ADJUSP_PAN混合使用,如果两个都没有设置,系统将根据窗口内容自动设置一个选项。
public static final int SOFT_INPUT_ADJUST_RESIZE = 0x10;


//输入法显示时平移窗口。它不需要处理尺寸变化,框架能够移动窗口以确保输入焦点可见。
//不可与SOFT_INPUT_ADJUST_RESIZE混合使用;如果两个都没设置,系统将根据窗口内容自动设置一个选项。
public static final int SOFT_INPUT_ADJUST_PAN = 0x20;


//当用户转至此窗口时,由系统自动设置,所以你不要设置它。
//当窗口显示之后该标志自动清除。
public static final int SOFT_INPUT_IS_FORWARD_NAVIGATION = 0x100;

  8. public int gravity;
       gravity 属性。什么是gravity属性呢?简单地说,就是窗口如何停靠。

       9. public float horizontalMargin;
       水平边距,容器与widget之间的距离,占容器宽度的百分率。

       10. public float verticalMargin;
       纵向边距。

       11. public int format;
       期望的位图格式。默认为不透明。参考android.graphics.PixelFormat。

       12. public int windowAnimations;
       窗口所使用的动画设置。它必须是一个系统资源而不是应用程序资源,因为窗口管理器不能访问应用程序。

       13. public float alpha = 1.0f;
       整个窗口的半透明值,1.0表示不透明,0.0表示全透明。

       14. public float dimAmount = 1.0f;
       当FLAG_DIM_BEHIND设置后生效。该变量指示后面的窗口变暗的程度。
       1.0表示完全不透明,0.0表示没有变暗。

       15. public float screenBrightness = -1.0f;
       用来覆盖用户设置的屏幕亮度。表示应用用户设置的屏幕亮度。
       从0到1调整亮度从暗到最亮发生变化。

       16. public IBinder token = null;
       窗口的标示符。( Identifier for this window. This will usually be filled in for you. )

       17. public String packageName = null;
       此窗口所在的包名。

       18. public int screenOrientation =ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
       屏幕方向,参见android.content.pm.ActivityInfo#screenOrientation。

       19. 在兼容模式下,备份/恢复参数所使用的内部缓冲区。
       public int[] mCompatibilityParamsBackup = null;


layoutanimation,顾名思义,是用来设置给viewgroup类型的animation,是子view来执行的。可以是

[java]  view plain copy
  1. android:layoutAnimation="@anim/popinlayout"   
也可以是javacode的

[java]  view plain copy
  1. viewgroup.setLayoutAnimation(layoutnaimationcontroller);  

和Animation类似,Layout Animation也支持Animation Listener,具体的就不多说了。layoutanimation会在View Group第一次进行布局的时候执行一次。

具体来说,layoutanimation支持三个参数,

1,anim就不多说了,

2,animationOrder,这个是说子view按照什么顺序来执行anim,可以使normal(正常,0-n),reverse(反序,n-0),random。一般不要太乱的还是normal

3,delay,用于延迟的每个子view的动画开始动画持续时间的浮点数。越大间隔越长。0.3或者30%的字样。


另外,LayoutAnimationController包含一个内部类,LayoutAnimationController.AnimationParameters,这个类主要包括了count和index两个参数。这些参数用于计算每个单独的视图动画的开始时间。

ViewGroup.LayoutParams这个类大家都一定很熟悉的,主要是height和width。其中还有一个字段,就是LayoutAnimationController.AnimationParameters,Used to animate layouts


layoutanimation一般可以用在listview等adapterview中,显得比较炫一些。

比如:

[html]  view plain copy
  1.     <ListView  
  2.         android:id="@+id/listview"  
  3.         android:layout_width="fill_parent"  
  4.         android:layout_height="fill_parent"  
  5. <strong>        android:persistentDrawingCache="animation|scrolling"   
  6.         android:layoutAnimation="@anim/scale_controller"strong>  
  7.         >  
  8.     ListView>  


listview中还有一个viewgroup的属性,android:persistentDrawingCache 

Defines the persistence of the drawing cache. The drawing cache might be enabled by a ViewGroup for all its children in specific situations (for instance during a scrolling.) This property lets you persist the cache in memory after its initial usage. Persisting the cache consumes more memory but may prevent frequent garbage collection is the cache is created over and over again. By default the persistence is set to scrolling. 

 定义绘图的高速缓存的持久性。 绘图缓存可能由一个 ViewGroup 在特定情况下为其所有的子类启用,例如在一个滚动的过程中。 此属性可以保留在内存中的缓存后其初始的使用。 坚持缓存会消耗更多的内存,但可能会阻止频繁的垃圾回收是反复创建缓存。 默认情况下持续存在设置为滚动。

其属性值只有以下几种:

ConstantValueDescription
none 0x0  The drawing cache is not persisted after use.
animation 0x1  The drawing cache is persisted after a layout animation.
scrolling 0x2The drawing cache is persisted after a scroll.
all 0x3  The drawing cache is always persisted.


一般默认的有scrolling属性,我们在有layoutAnimation动画的时候添加上animation属性会更流通些。


LayoutAnimationController用于为一个layout里面的控件,或者是一个ViewGroup里面的控件设置动画效果,可以在XML文件中设置,亦可以在Java代码中设置。

一种直接在XML文件中设置

1.  res/anim文件夹下新建一个XML文件,名为list_anim_layout.xml,

[java]  view plain copy
  1. "http://schemas.android.com/apk/res/android"  
  2.         android:delay="30%"  
  3.         android:animationOrder="reverse"  
  4.         android:animation="@anim/slide_right" />  

android:delay  子类动画时间间隔 (延迟)   70% 也可以是一个浮点数 如“1.2”等

android:animationOrder="random"   子类的显示方式 random表示随机

android:animationOrder 的取值有 

normal 0    默认
reverse 1   倒序
random 2   随机

android:animation="@anim/slide_right" 表示孩子显示时的具体动画是什么


说明:其中delay的单位为秒;animation为设置动画的文件。animationOrder为进入方式

2.  res/anim文件夹下新建一个XML文件,名为slide_right,即上面用到的文件。

[html]  view plain copy
  1.     <set xmlns:android="http://schemas.android.com/apk/res/android"   
  2.         android:interpolator="@android:anim/accelerate_interpolator">  
  3.     <translate android:fromXDelta="-100%p" android:toXDelta="0"  
  4.             android:duration="@android:integer/config_shortAnimTime" />  
  5. set>  

 显示的效果为ListView第一次出现的时候为 item随机出现 每个Item都是从左不可见(-100%p)的区域向右滑动到显示的地方

3.  在主布局文件中为控件添加如下配置:

android:layoutAnimation="@anim/list_anim_layout",即第一步的布局文件。


第二种设置方法:在Java代码中设置

1. 同上;

2. 同上;

4.  Acitivty中添加如下代码:


//通过加载XML动画设置文件来创建一个Animation对象;

       Animation animation=AnimationUtils.loadAnimation(this, R.anim.list_anim);

       //得到一个LayoutAnimationController对象;

       LayoutAnimationController lac=new LayoutAnimationController(animation);

       //设置控件显示的顺序;

       lac.setOrder(LayoutAnimationController.ORDER_REVERSE);

       //设置控件显示间隔时间;

       lac.setDelay(1);

       //ListView设置LayoutAnimationController属性;

   datalist.setLayoutAnimation(lac);


有两种用法,我的通常写在代码中,像下面这样: 

Java代码   收藏代码
  1. /** 
  2.      * Layout动画 
  3.      *  
  4.      * @return 
  5.      */  
  6.     protected LayoutAnimationController getAnimationController() {  
  7.         int duration=300;  
  8.         AnimationSet set = new AnimationSet(true);  
  9.   
  10.         Animation animation = new AlphaAnimation(0.0f, 1.0f);  
  11.         animation.setDuration(duration);  
  12.         set.addAnimation(animation);  
  13.   
  14.         animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,  
  15.                 Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,  
  16.                 -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);  
  17.         animation.setDuration(duration);  
  18.         set.addAnimation(animation);  
  19.   
  20.         LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);  
  21.         controller.setOrder(LayoutAnimationController.ORDER_NORMAL);  
  22.         return controller;  
  23.     }  


应用的时候只需这样: 
Java代码   收藏代码
  1. listView = (ListView) findViewById(R.id.listView);  
  2. listView.setLayoutAnimation(getAnimationController());  
  3. adapter = new ListViewAdapter(stores);  
  4. listView.setAdapter(adapter);  


这样一个简单的LayoutAnimation就完成了。 

别看到这里就以为文章就完了,以上都是些小玩意。呵呵,还有更厉害的! 

你想设置更炫的动画吗?LayoutAnimation通常是Item一个一个的出现,有某种规律的。想让每个Item都有自己的动画吗?那就继续看下去。 
Java代码   收藏代码
  1. .......  
  2. private int duration=1000;  
  3.         private Animation push_left_in,push_right_in;  
  4.         private Animation slide_top_to_bottom,slide_bottom_to_top;  
  5.         public ListViewAdapter(ArrayList list) {  
  6.             this.list = list;  
  7.             push_left_in=AnimationUtils.loadAnimation(context, R.anim.push_left_in);  
  8.             push_right_in=AnimationUtils.loadAnimation(context, R.anim.push_right_in);  
  9.             slide_top_to_bottom=AnimationUtils.loadAnimation(context, R.anim.slide_top_to_bottom);  
  10.             slide_bottom_to_top=AnimationUtils.loadAnimation(context, R.anim.slide_bottom_to_top);  
  11.         }  
  12. ........  
  13.   
  14. @Override  
  15.         public View getView(int position, View convertView, ViewGroup parent) {  
  16.             // TODO Auto-generated method stub  
  17.             ViewHodler hodler;  
  18.             if (convertView == null) {  
  19.                 hodler = new ViewHodler();  
  20.                 convertView = LayoutInflater.from(context).inflate(  
  21.                         R.layout.simple_item_7_for_main, null);  
  22.                 ........  
  23.                   
  24.                   
  25.                 convertView.setTag(hodler);  
  26.                   
  27.                 if (position % 2 == 0) {  
  28.                     push_left_in.setDuration(duration);  
  29.                     convertView.setAnimation(push_left_in);  
  30.                 } else {  
  31.                     push_right_in.setDuration(duration);  
  32.                     convertView.setAnimation(push_right_in);  
  33.                 }  
  34.                   
  35.                 /*if(position==0){ 
  36.                     slide_bottom_to_top.setDuration(duration); 
  37.                     convertView.setAnimation(slide_bottom_to_top); 
  38.                 } 
  39.                 else{ 
  40.                     slide_top_to_bottom.setDuration(duration); 
  41.                     convertView.setAnimation(slide_top_to_bottom); 
  42.                 }*/  
  43.                   
  44.             }else{  
  45.                 hodler = (ViewHodler) convertView.getTag();  
  46.             }  
  47. ........  
  48.               
  49.               
  50.             return convertView;  
  51.         }  

看见上面的动画设置了吗?将动画写在getView()中,这样可以设置很多不同的动画。其实这不属于LayoutAnimation的范畴了。 
你可以试一下,如果设计好的话,可以有比LayoutAnimation更酷的效果。 
我这里只试了两种效果。 
下面是我的动画文件,共四个: 
第一种效果:item分别从左右两侧滑入效果。 
push_left_in.xml 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="300"/>  
  4.     <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />  
  5. set>  

push_right_in.xml 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>  
  4.     <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />  
  5. set>  


第2种效果:第一个item从下往上滑入,其他Item从上往下滑入效果,这个效果如果单个Item比较高(height)的话效果非常酷(卡牛的老版本好像用的就是这种效果)。 
slide_bottom_to_top.xml 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">  
  3.     <translate android:fromYDelta="100%" android:toXDelta="0" android:duration="300" />  
  4.     <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />  
  5. set>  

slide_top_to_bottom.xml 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">  
  3.     <translate android:fromYDelta="-100%" android:toXDelta="0" android:duration="300" />  
  4.     <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />  
  5. set>  


另外一篇: 
这个不是我写的。 
GridView的item从上下左右飞入  
Java代码   收藏代码
  1. import java.util.Random;  
  2. import android.app.Activity;  
  3. import android.content.Context;  
  4. import android.os.Bundle;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.view.ViewGroup;  
  9. import android.view.animation.Animation;  
  10. import android.view.animation.TranslateAnimation;  
  11. import android.widget.BaseAdapter;  
  12. import android.widget.Button;  
  13. import android.widget.GridView;  
  14. import android.widget.ImageView;  
  15. public class ZdemoActivity extends Activity {  
  16.    
  17.  private GridView gv;  
  18.  private Button btn;  
  19.  private TranslateAnimation taLeft, taRight, taTop, taBlow;  
  20.  private int[] imgList = new int[15];  
  21.  private MyAdapter mAdapter;  
  22.  private LayoutInflater mInflater;  
  23.  @Override  
  24.  public void onCreate(Bundle savedInstanceState) {  
  25.   super.onCreate(savedInstanceState);  
  26.   setContentView(R.layout.main);  
  27.   this.InitView();  
  28.   this.InitAnima();  
  29.   this.InitData();  
  30.  }  
  31.  private void InitAnima() {  
  32.   // TODO Auto-generated method stub  
  33.   taLeft = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1.0f,  
  34.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  35.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  36.     Animation.RELATIVE_TO_PARENT, 0.0f);  
  37.   taRight = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1.0f,  
  38.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  39.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  40.     Animation.RELATIVE_TO_PARENT, 0.0f);  
  41.   taTop = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,  
  42.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  43.     Animation.RELATIVE_TO_PARENT, 1.0f,  
  44.     Animation.RELATIVE_TO_PARENT, 0.0f);  
  45.   taBlow = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,  
  46.     Animation.RELATIVE_TO_PARENT, 0.0f,  
  47.     Animation.RELATIVE_TO_PARENT, -1.0f,  
  48.     Animation.RELATIVE_TO_PARENT, 0.0f);  
  49.   taLeft.setDuration(1000);  
  50.   taRight.setDuration(1000);  
  51.   taTop.setDuration(1000);  
  52.   taBlow.setDuration(1000);  
  53.  }  
  54.  private void InitData() {  
  55.   // TODO Auto-generated method stub  
  56.   for (int i = 0; i < 15; i++) {  
  57.    imgList[i] = R.drawable.ic_launcher;  
  58.   }  
  59.   mAdapter = new MyAdapter();  
  60.   gv.setAdapter(mAdapter);  
  61.  }  
  62.  private void InitView() {  
  63.   // TODO Auto-generated method stub  
  64.   gv = (GridView) findViewById(R.id.gridView1);  
  65.   btn = (Button) findViewById(R.id.button1);  
  66.   btn.setOnClickListener(new OnClickListener() {  
  67.    @Override  
  68.    public void onClick(View v) {  
  69.     // TODO Auto-generated method stub  
  70.     mAdapter = null;  
  71.     mAdapter = new MyAdapter();  
  72.     gv.setAdapter(mAdapter);  
  73.     mAdapter.notifyDataSetChanged();  
  74.    }  
  75.   });  
  76.   mInflater = (LayoutInflater) this  
  77.     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  78.  }  
  79.  private class MyAdapter extends BaseAdapter {  
  80.   @Override  
  81.   public int getCount() {  
  82.    // TODO Auto-generated method stub  
  83.    return imgList.length;  
  84.   }  
  85.   @Override  
  86.   public Object getItem(int position) {  
  87.    // TODO Auto-generated method stub  
  88.    return imgList[position];  
  89.   }  
  90.   @Override  
  91.   public long getItemId(int position) {  
  92.    // TODO Auto-generated method stub  
  93.    return position;  
  94.   }  
  95.   @Override  
  96.   public View getView(int position, View convertView, ViewGroup parent) {  
  97.    // TODO Auto-generated method stub  
  98.    ViewHolder holder = null;  
  99.    if (convertView == null) {  
  100.     convertView = mInflater.inflate(R.layout.item, null);  
  101.     holder = new ViewHolder();  
  102.     holder.image = (ImageView) convertView  
  103.       .findViewById(R.id.imageView1);  
  104.     convertView.setTag(holder);  
  105.    } else {  
  106.     holder = (ViewHolder) convertView.getTag();  
  107.    }  
  108.    int imgID = imgList[position];  
  109.    holder.image.setImageResource(imgID);  
  110.    Random ran = new Random();  
  111.    int rand = ran.nextInt(4);  
  112.    switch (rand) {  
  113.    case 0:  
  114.     convertView.startAnimation(taLeft);  
  115.     break;  
  116.    case 1:  
  117.     convertView.startAnimation(taRight);  
  118.     break;  
  119.    case 2:  
  120.     convertView.startAnimation(taTop);  
  121.     break;  
  122.    case 3:  
  123.     convertView.startAnimation(taBlow);  
  124.     break;  
  125.    }  
  126.    return convertView;  
  127.   }  
  128.   class ViewHolder {  
  129.    public ImageView image;  
  130.   }  
  131.  }  




一、            ViewGroup1.1         概述 
定义 
public abstract class ViewGroup extends View implements ViewParent, ViewManager 
所在的包 
import android.view.ViewGroup; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
       |      |___ AbsListView 
       |      |      |___ GridView 
       |      |      |___ ListView 
       |      |             |___ ExpandableListView 
       |      |___ AbsSpinner 
       |             |___ Gallery 
       |             |___ Spinner 
       |___ FrameLayout 
       |      |___ DatePicker 
       |      |___ TimePicker 
       |      |___ MediaController 
       |      |___ ScrollView 
       |      |___ TabHost 
       |      |___ ViewAnimator 
       |             |___ ViewFlipper 
       |             |___ ViewSwitcher 
       |                    |___ ImageSwitcher 
       |                    |___ TextSwitcher 
       |___ LinearLayout 
       |      |___ RadioGroup 
       |      |___ TabWidget 
       |      |___ TableLayout 
       |      |___ TableRow 
       |      |___ ZoomControls 
       |___ RelativeLayout 
       |      |___ DialerFilter 
       |      |___ TwoLineListItem 
       |___ AbsoluteLayout 
              |___ WebView 
ViewGroup继承View,是一组view的集合,通过addView()来添加child view,removeView()、removeAllViews()等删除child view。addView()加入的view存为数组,初始化数组大小为12,超过大小时每次增加12,每一个index对应一个view,可以通过getChildAt()、indexOfChild()来获取view和index,getChildCount()获取总child数。 
内部类LayoutParams来管理ViewGroup的所占区域大小。 
FILL_PARENT:填充满parent的宽或高 
WRAP_CONTENT:内容的实际大小加边距 
offsetChildrenTopAndBottom()、setPadding()来设置边距。 
1.2         部分方法 
void addView(View child) 
void addView(View child, int index) 
void addView(View child, int width, int height) 
void addView(View child, LayoutParams params) 
void addView(View child, int index, LayoutParams params) 
void removeView(View view) 
void removeViewAt(int index) 
void removeViews(int start, int count) 
void removeAllViews() 
void removeViewInLayout(View view) 
void removeViewsInLayout(int start, int count) 
void removeAllViewsInLayout() 
增加删除child view 
void offsetChildrenTopAndBottom(int offset) 
设置垂直方向顶部和底部的偏移,单位象素 
int getChildCount() 
int indexOfChild(View child) 
View getChildAt(int index) 
void setDescendantFocusability(int focusability) 
int getDescendantFocusability() 
ViewGroup.FOCUS_BEFORE_DESCENDANTS 
先于子孙获得focus 
ViewGroup.FOCUS_AFTER_DESCENDANTS 
子孙都不需要focus时viewgroup才获得 
ViewGroup.FOCUS_BLOCK_DESCENDANTS 
void setClipChildren(boolean clipChildren) 
void setClipToPadding(boolean clipToPadding) 
true:滚动时child不可以绘制到padding区域,即剪裁掉 
false:滚动时child可以绘制到padding区域 
void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) 
设置child有add或remove时触发的监听器 
void startLayoutAnimation() 
运行动画 
void scheduleLayoutAnimation() 
设置动画状态,刷新时运行动画 
void setLayoutAnimation(LayoutAnimationController controller) 
LayoutAnimationController getLayoutAnimation() 
设置布局动画,在child第一次布局时运行动画 
void setLayoutAnimationListener(Animation.AnimationListener animationListener) 
Animation.AnimationListener getLayoutAnimationListener() 
设置动画播放开始、结束、重播时触发的监听器 
boolean isAnimationCacheEnabled() 
void setAnimationCacheEnabled(boolean enabled) 
boolean isAlwaysDrawnWithCacheEnabled() 
void setAlwaysDrawnWithCacheEnabled(boolean always) 
int getPersistentDrawingCache() 
void setPersistentDrawingCache(int drawingCacheToKeep) 
1.3         ViewGroup.LayoutParams 
public static class LayoutParams 
ViewGroup.LayoutParams 
|___ ViewGroup.MarginLayoutParams 
|      |___ FrameLayout.LayoutParams 
|      |___ LinearLayout.LayoutParams 
|      |      |___ RadioGroup.LayoutParams 
|      |      |___ TableLayout.LayoutParams 
|      |      |___ TableRow.LayoutParams 
|      |___ RelativeLayout.LayoutParams 
|___ AbsoluteLayout.LayoutParams 
|___ AbsListView.LayoutParams 
|___ Gallery.LayoutParams 
|___ WindowManager.LayoutParams 
public int width;     //指定view的宽高 
public int height; 
public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 
ViewGroup.LayoutParams.FILL_PARENT 
ViewGroup.LayoutParams.WRAP_CONTENT 
public LayoutParams(Context c, AttributeSet attrs) 
public LayoutParams(int width, int height) 
public LayoutParams(LayoutParams source) 
LayoutParams() 
1.4         ViewGroup. MarginLayoutParams 
public static class MarginLayoutParams extends ViewGroup.LayoutParams 
public int leftMargin;     //在ViewGroup.LayoutParams基础上增加4个方向边距 
public int topMargin; 
public int rightMargin; 
public int bottomMargin; 
public MarginLayoutParams(Context c, AttributeSet attrs) 
public MarginLayoutParams(int width, int height) 
public MarginLayoutParams(MarginLayoutParams source) 
public MarginLayoutParams(LayoutParams source) 
public void setMargins(int left, int top, int right, int bottom) 
        Margin        Padding、大小为设置的width, height,背景绘制的区域        实体大小 

通过ViewGroup.LayoutParams设置width,height 
View.setLayoutParams(ViewGroup.LayoutParams params); 
通过ViewGroup.MarginLayoutParams设置margin 
ViewGroup.MarginLayoutParams.setMargins(int left, int top, int right, int bottom); 
ViewGroup.MarginLayoutParams.leftMargin 
通过View. setPadding(int left, int top, int right, int bottom); 设置padding 
白色区域大小:    width+ leftMargin+ rightMargin 
                            height+ topMargin+ bottomMargin 
橙色区域大小:    width 
                            height 
绿色区域大小:    width- leftPadding- rightPadding 
                            height- topPadding- bottomPadding 

二、            AdapterView2.1         概述 
定义 
public abstract class AdapterView extends ViewGroup 
包路径 
import android.widget.AdapterView; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsListView 
              |      |___ GridView 
              |      |___ ListView 
              |             |___ ExpandableListView 
              |___ AbsSpinner 
                     |___ Gallery 
                     |___ Spinner 
AdapterView继承ViewGroup,但AdapterView的child view由Adapter决定,不能通过addView()来添加。 
setAdapter()来设置Adapter,getAdapter()获取。 
2.2         部分方法 
void addView(View child) 
void addView(View child, int index) 
void addView(View child, LayoutParams params) 
void addView(View child, int index, LayoutParams params) 
void removeView(View child) 
void removeViewAt(int index) 
void removeAllViews() 
不支持添加删除view,使用则抛出UnsupportedOperationException异常 
void setOnClickListener(OnClickListener l) 
不支持,抛出异常RuntimeException 
abstract T getAdapter() 
abstract void setAdapter(T adapter) 
设置child的数据和view 
int getCount() 
int getPositionForView(View view) 
long getItemIdAtPosition(int position) 
Object getItemAtPosition(int position) 
返回Object不一定就是一个item的view,跟getAdapter().getItem(position)等效 
要想获得view应getAdapter().getView(position, convertView, parent) 
abstract View getSelectedView() 
int getSelectedItemPosition() 
long getSelectedItemId() 
Object getSelectedItem() 
abstract void setSelection(int position) 
int getFirstVisiblePosition() 
屏幕上可见的第一项的position,部分可见也算 
int getLastVisiblePosition() 
屏幕上可见的最后一项的position,部分可见也算 
void setFocusable(boolean focusable) 
void setFocusableInTouchMode(boolean focusable) 
void setOnItemClickListener(OnItemClickListener listener) 
final OnItemClickListener getOnItemClickListener() 
设置item点击监听器 
boolean performItemClick(View view, int position, long id) 
调用item点击监听器设置的回调函数 
void setOnItemLongClickListener(OnItemLongClickListener listener) 
final OnItemLongClickListener getOnItemLongClickListener() 
设置item长按监听器 
void setOnItemSelectedListener(OnItemSelectedListener listener) 
final OnItemSelectedListener getOnItemSelectedListener() 
设置item被选择时触发的监听器 
public void setTextFilterEnabled(boolean textFilterEnabled) 
public boolean isTextFilterEnabled() 
开启或关闭过滤窗口,开启时,键盘输入显示在屏幕下方一半透明黑色区域,根据输入过滤掉不包含输入文字的项

二、            Adapter3.1         概述 
定义 
public interface Adapter 
包路径 
import android.widget.Adapter; 
SpinnerAdapter 
ListAdapter 
HeaderViewListAdapter 
BaseAdapter 
WrapperListAdapter 
CursorAdapter 
ArrayAdapter 
SimpleAdapter 
Adapter 
ResourceCursorAdapter 
SimpleCursorAdapter 
黑色文字为接口红色文字为类斜体字为抽象类 
子类信息 
Adapter是AdapterView和数据间的桥梁,提供访问每项数据的接口,并为每项创建一个view。 
3.2         部分方法 
void unregisterDataSetObserver(DataSetObserver observer); 
void registerDataSetObserver(DataSetObserver observer) 
注册一个observer,当该Adapter对象的数据变化时调用。 
int getCount() 
Object getItem(int position) 
long getItemId(int position)      
boolean hasStableIds() 
item的id是否稳定。稳定则数据变化时item 的id不变 
View getView(int position, View convertView, ViewGroup parent) 
返回显示position项数据的view,可以手动创建一个view也可以通过xml layout文件创建。 
position          第position项 
convertView   可以为null,送入一个view,如果这个view不能转换为需要显示的view则创建一个新的view 
parent            返回的view加入parent的ViewGroup 
int getViewTypeCount() 
getView()返回view的种数,如果都返回同一类的view则getViewTypeCount()为1 
int getItemViewType(int position) 
获得position项view的类型,可以的返回值有0到getViewTypeCount() – 1和IGNORE_ITEM_VIEW_TYPE 
boolean isEmpty() 
是否包含有数据 
ListAdapter增加 
boolean isEnabled(int position) 
public boolean areAllItemsEnabled() 
返回false表示item不可选,不可点击 
SpinnerAdapter增加 
public View getDropDownView(int position, View convertView, ViewGroup parent) 
position项下拉菜单的view 
3.3         ArrayAdapter 
class ArrayAdapter extends BaseAdapter implements Filterable 
ArrayAdapter(Context context, int textViewResourceId) 
ArrayAdapter(Context context, int textViewResourceId, T[] objects) 
ArrayAdapter(Context context, int textViewResourceId, List objects) 
ArrayAdapter(Context context, int resource, int textViewResourceId) 
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) 
ArrayAdapter(Context context, int resource, int textViewResourceId, List objects) 
context 
textViewResourceId 
没有resource参数时:含有TextView 的layout文件资源ID,创建view时使用; 
有resource参数时:layout文件中TextView的ID 
resource 
loyout文件资源ID 
objects 
ListView显示的对象 
SDK自带的textViewResourceId对应的xml文件在cupcake\frameworks\base\core\res\res\layout 
android.R.layout.simple_list_item_1 
TextView 
android.R.layout.simple_list_item_2 
含有两个TextView的TwoLineListItem 
android.R.layout. simple_expandable_list_item_1 
TextView 
android.R.layout. simple_expandable_list_item_2 
含有两个TextView的TwoLineListItem 
android.R.layout. simple_list_item_single_choice 
CheckedTextView 
android.R.layout. simple_list_item_multiple_choice 
CheckedTextView 
android.R.layout. simple_list_item_checked 
CheckedTextView 
void add(T object) 
void insert(T object, int index) 
void remove(T object) 
void clear() 
void notifyDataSetChanged() 
void setNotifyOnChange(boolean notifyOnChange) 
列表发生改变时是否自动调用notifyDataSetChanged(),设为false则需手动调用 
Context getContext() 
void setDropDownViewResource(int resource) 
设置创建下拉菜单view需要的layout资源文件 
static ArrayAdapter createFromResource(Context context, 
            int textArrayResId, int textViewResId) 
Filter getFilter() 
3.4         SimpleAdapter 
public class SimpleAdapter extends BaseAdapter implements Filterable 
public SimpleAdapter(Context context, List<? extends Map> data, 
            int resource, String[] from, int[] to) 
context 
data 
resource 
Layout文件id 
from 
data中Map的key 
to 
生成itemView的id, to[]数组大小不能超过from []的大小 
public void setDropDownViewResource(int resource) 
设置创建下拉菜单view需要的layout资源文件 
public ViewBinder getViewBinder() 
public void setViewBinder(ViewBinder viewBinder) 
public static interface ViewBinder { 
boolean setViewValue(View view, Object data, String textRepresentation); 

绑定数据到view 
用setViewBinder(null)的方式取消绑定 
public void setViewImage(ImageView v, int value) 
public void setViewImage(ImageView v, String value) 
public void setViewText(TextView v, String text) 
public Filter getFilter() 
3.5         SimpleCursorAdapter 
public class SimpleCursorAdapter extends ResourceCursorAdapter 
demo 
aipDemos/com.example.android.view/List2.java 
List2.java,List3.java,List7.java 
菜单路径:API Demos/Views/Lists/ 
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) 
context 
layout 

Curor 
from 
to 
public View newView(Context context, Cursor cursor, ViewGroup parent) 
public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) 
public ViewBinder getViewBinder() 
public void setViewBinder(ViewBinder viewBinder) 
public void setViewImage(ImageView v, String value) 
public void setViewText(TextView v, String text) 
public void bindView(View view, Context context, Cursor cursor) 
public int getStringConversionColumn() 
public void setStringConversionColumn(int stringConversionColumn) 
设置获取from[stringConversionColumn]中数据 
public CursorToStringConverter getCursorToStringConverter() 
public void setCursorToStringConverter( 
CursorToStringConverter cursorToStringConverter) 
public static interface CursorToStringConverter { 
CharSequence convertToString(Cursor cursor); 

public CharSequence convertToString(Cursor cursor) 
获取from[stringConversionColumn]中数据 
public void changeCursor(Cursor c) 
3.6         HeaderViewListAdapter 
public class HeaderViewListAdapter implements WrapperListAdapter, Filterable 
private ListAdapter mAdapter; 
ArrayList mHeaderViewInfos; 
ArrayList mFooterViewInfos; 
public HeaderViewListAdapter(ArrayList headerViewInfos, 
ArrayList footerViewInfos, 
ListAdapter adapter) 
headerViewInfos 
footerViewInfos 
adapter 
public class FixedViewInfo { 
public View view; 
public Object data; 
public boolean isSelectable; 

public int getHeadersCount() 
public int getFootersCount() 
public int getCount() 
Header,Footer,mAdapter总item数 
public boolean isEmpty() 
mAdapter是否为空 
public boolean removeHeader(View v) 
public boolean removeFooter(View v) 
public boolean areAllItemsEnabled() 
public ListAdapter getWrappedAdapter() 
获取mAdapter 

四、            AbsListView4.1         概述 
定义 
public abstract class AbsListView extends AdapterView implements TextWatcher, 
        ViewTreeObserver.OnGlobalLayoutListener, Filter.FilterListener, 
        ViewTreeObserver.OnTouchModeChangeListener 
包路径 
import android.widget.AbsListView; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsListView 
                     |___ GridView 
                     |___ ListView 
                            |___ ExpandableListView 
4.2         部分方法 
void setStackFromBottom(boolean stackFromBottom) 
boolean isStackFromBottom() 
单列 
多列 
Disable 
Enable 
Disable 
Enable 














void setScrollingCacheEnabled(boolean enabled) 
boolean isScrollingCacheEnabled() 
设置是否缓存卷动项,缓存则需额外的内存,缺省为enable 
void setCacheColorHint(int color) 
int getCacheColorHint() 
int getSolidColor() 
缓存项背景颜色 
int pointToPosition(int x, int y) 
返回包含坐标(x, y)的项,没有项包含该点则返回INVALID_POSITION 
long pointToRowId(int x, int y) 
void setTranscriptMode(int mode) 
int getTranscriptMode() 
TRANSCRIPT_MODE_DISABLED 
当数据发生变化不自动滚动 
TRANSCRIPT_MODE_NORMAL 
当数据发生变化时,最后一项正显示在屏幕上,自动滚动到最低端 
TRANSCRIPT_MODE_ALWAYS_SCROLL 
当数据发生变化时,自动滚动到最低端 
void setFilterText(String filterText) 
void clearTextFilter() 
boolean hasTextFilter() 
过滤文本 
void getFocusedRect(Rect r) 
获取焦点框区域 
View getSelectedView() 
void setSelector(int resID) 
void setSelector(Drawable sel) 
Drawable getSelector() 
焦点框 
void setDrawSelectorOnTop(boolean onTop) 
true:Selector绘制在文字之上 
void setScrollIndicators(View up, View down) 
void reclaimViews(List views) 
void setRecyclerListener(RecyclerListener listener) 
LayoutParams generateLayoutParams(AttributeSet attrs) 
void beforeTextChanged(CharSequence s, int start, int count, int after) 
void onTextChanged(CharSequence s, int start, int before, int count) 
void afterTextChanged(Editable s) 

五、            ListView5.1         概述 
定义 
public class ListView extends AbsListView 
包路径 
import android.widget.ListView 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsListView 
                     |___ ListView 
                            |___ ExpandableListView 
ListView显示为垂直可滚动的一列,所有item由ListAdapter提供。 
5.2         部分方法 
public ListView(Context context) 
public ListView(Context context, AttributeSet attrs) 
public ListView(Context context, AttributeSet attrs, int defStyle) 
ListAdapter getAdapter() 
void setAdapter(ListAdapter adapter) 
设置listitem,adapter包含每一个item的数据并提供显示数据的view 
void addHeaderView(View v, Object data, boolean isSelectable) 
void addHeaderView(View v) 
在list顶端加headView,可以加多个,按添加的顺序显示。isSelectable为可否被选择。 
必须在setAdapter()前调用,否则抛出IllegalStateException异常 
int getHeaderViewsCount() 
获得headerView的数量 
boolean removeHeaderView(View v) 
必须在setAdapter()后调用,否则抛出NullPointerException异常(运行期异常)。 
void addFooterView(View v, Object data, boolean isSelectable) 
void addFooterView(View v) 
在list尾添加footerView,同addHeaderView() 
必须在setAdapter()前后调用都可以 
int getFooterViewsCount() 
获得footerView的数量 
boolean removeFooterView(View v) 
必须在setAdapter()后调用,否则抛出NullPointerException异常(运行期异常)。 
int getChoiceMode() 
void setChoiceMode(int choiceMode) 
ListView. CHOICE_MODE_NONE 
ListView. CHOICE_MODE_SINGLE 
ListView. CHOICE_MODE_MULTIPLE 
void setSelection(int position) 
设置第position为选择状态 
void setSelectionFromTop(int position, int y) 
设置第position为选择状态,使position那项的位置在距离ListView顶端y的位置 
void setSelectionAfterHeaderView() 
使选择项位置紧挨着HeaderView。 
void setItemsCanFocus(boolean itemsCanFocus) 
boolean getItemsCanFocus() 
Drawable getDivider() 
void setDivider(Drawable divider) 
设置每两个item间的分割 
int getDividerHeight() 
void setDividerHeight(int height) 
设置每两个item间空隙的高度 
boolean isItemChecked(int position) 
在单选或多选状态下判断第position项状态 
int getCheckedItemPosition() 
在单选状态下获取选择的那项,多选无效 
SparseBooleanArray getCheckedItemPositions() 
非单选模式下有效 
void clearChoices() 
清除选择 
void setItemChecked(int position, boolean value) 
设置position项的状态 
Parcelable onSaveInstanceState() 
void onRestoreInstanceState(Parcelable state) 
boolean performItemClick(View view, int position, long id) 
boolean onTouchEvent(MotionEvent ev) 
boolean dispatchKeyEvent(KeyEvent event) 
boolean onKeyDown(int keyCode, KeyEvent event) 
boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) 
onKeyUp(int keyCode, KeyEvent event) 

六、            ExpandableListView6.1         概述 
定义 
public class ExpandableListView extends ListView 
包路径 
import android.widget.ExpandableListView; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsListView 
                     |___ ListView 
                            |___ ExpandableListView 
ExpandableListView显示为垂直可滚动的一列,与ListView的区别是它的item分group和child两层,item的children可以展开显示,也可以叠起不显示。所有item由ExpandableListAdapter提供。 
ExpandableListItem的展开与否可以用setChildIndicator()或setGroupIndicator()来设置。 
注意:如果ExpandableListView的parent高度设为WRAP_CONTENT,则不能指定ExpandableListView的layout_height为WRAP_CONTENT;如果parent高度一定则可以设为WRAP_CONTENT。 
6.2         部分方法 
void setAdapter(ListAdapter adapter) 
抛出异常RuntimeException 
ListAdapter getAdapter() 
只获取groupList 
void setAdapter(ExpandableListAdapter adapter) 
ExpandableListAdapter getExpandableListAdapter() 
设置ExpandableListView数据 
boolean collapseGroup(int groupPos) 
合上groupPosition组, 
boolean expandGroup(int groupPos) 
展开groupPosition组,是展开状态返回true 
boolean isGroupExpanded(int groupPosition) 
long getExpandableListPosition(int flatListPosition) 
转换一个ListView的position(flatListPosition)为ExpandableList的packedPosition,packedPosition由ExpandableList的groupPosition和childPosition计算而来。 
int getFlatListPosition(long packedPosition) 
packedPosition转换为flatListPosition, 
packedPosition类型为group时packedPosition跟groupPosition相等 
packedPosition类型为child时packedPosition跟child所在的group的groupPosition相等 
static int getPackedPositionType(long packedPosition) 
packedPosition的类型,groupPosition还是childPosition 
ExpandableListView.PACKED_POSITION_TYPE_GROUP 
ExpandableListView.PACKED_POSITION_TYPE_CHILD 
ExpandableListView.PACKED_POSITION_TYPE_NULL 
static int getPackedPositionGroup(long packedPosition) 
返回groupPosition 
static int getPackedPositionChild(long packedPosition) 
如果packedPosition的类型是PACKED_POSITION_TYPE_CHILD,返回childPosition 
static long getPackedPositionForChild(int groupPosition, int childPosition) 
生成child的packedPosition 
static long getPackedPositionForGroup(int groupPosition) 
生成group的packedPosition 
long getSelectedPosition() 
long getSelectedId() 
void setGroupIndicator(Drawable groupIndicator) 
groupItem的标识 
void setIndicatorBounds(int left, int right) 
groupItem标识的位置 
void setChildIndicator(Drawable childIndicator) 
childItem的标识 
void setChildIndicatorBounds(int left, int right) 
childItem标识的位置,从left开始到right结束,right>left才显示出来 
left,right都可以指定ExpandableListView.CHILD_INDICATOR_INHERIT,继承groupItem表识的位置,即通过setIndicatorBounds()设置的位置 
void setChildDivider(Drawable childDivider) 
void setSelectedGroup(int groupPosition) 
boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) 
public void setOnChildClickListener(OnChildClickListener onChildClickListener) 
设置childItem点击监听器 
public void setOnGroupClickListener(OnGroupClickListener onGroupClickListener) 
设置groupItem点击监听器 
public void setOnGroupCollapseListener ( 
OnGroupCollapseListener onGroupCollapseListener) 
设置groupItem合上时触发的监听器 
public void setOnGroupExpandListener ( 
                   OnGroupExpandListener onGroupExpandListener) 
设置groupItem展开时触发的监听器 
public void setOnItemClickListener(OnItemClickListener l) 
触发ItemClick的itemPos是flatListPosition,尽量用setOnChildClickListener()和setOnGroupClickListener()代替这个方法。 
6.3         ExpandableListAdapter 
BaseExpandableListAdapter 
CursorTreeAdapter 
SimpleExpandableListAdapter 
ResourceCursorTreeAdapter 
ExpandableListAdapter 
SimpleCursorTreeAdapter 
黑色文字为接口红色文字为类斜体字为抽象类 

6.4         SimpleExpandableListAdapter 
public class SimpleExpandableListAdapter extends BaseExpandableListAdapter 
public SimpleExpandableListAdapter(Context context, 
            List<? extends Map> groupData, int groupLayout, 
            String[] groupFrom, int[] groupTo, 
            List<? extends List<? extends Map>> childData, 
            int childLayout, String[] childFrom, int[] childTo) 
public SimpleExpandableListAdapter(Context context, 
            List<? extends Map> groupData, int expandedGroupLayout, 
            int collapsedGroupLayout, String[] groupFrom, int[] groupTo, 
            List<? extends List<? extends Map>> childData, 
            int childLayout, String[] childFrom, int[] childTo) 
public SimpleExpandableListAdapter(Context context, 
            List<? extends Map> groupData, int expandedGroupLayout, 
            int collapsedGroupLayout, String[] groupFrom, int[] groupTo, 
            List<? extends List<? extends Map>> childData, 
            int childLayout, int lastChildLayout, String[] childFrom, 
            int[] childTo) 
groupData 
grouplist数据 
groupLayout 
grouplist loyout资源文件 
expandedGroupLayout 
grouplist 
collapsedGroupLayout 
grouplist 
groupFrom 
抽取groupData的Map的哪几列数据 
groupTo 
由groupFrom获取的数据生成view的viewId 
childData 
childlist数据 
childLayout 
childlistloyout资源文件 
lastChildLayout 
childFrom 
抽取childlist的Map的哪几列数据 
childTo 
由childFrom获取的数据生成view的viewId 
public int getChildrenCount(int groupPosition) 
public Object getChild(int groupPosition, int childPosition) 
public long getChildId(int groupPosition, int childPosition) 
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, 
            View convertView, ViewGroup parent) 
public View newChildView(boolean isLastChild, ViewGroup parent) 
public int getGroupCount() 
public Object getGroup(int groupPosition) 
public long getGroupId(int groupPosition) 
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, 
            ViewGroup parent) 
public View newGroupView(boolean isExpanded, ViewGroup parent) 
public boolean isChildSelectable(int groupPosition, int childPosition) 
public boolean hasStableIds() 
6.5         SimpleCursorTreeAdapter 
public abstract class SimpleCursorTreeAdapter extends ResourceCursorTreeAdapter 
public SimpleCursorTreeAdapter(Context context, Cursor cursor, int collapsedGroupLayout, 
            int expandedGroupLayout, String[] groupFrom, int[] groupTo, int childLayout, 
            int lastChildLayout, String[] childFrom, int[] childTo) 
public SimpleCursorTreeAdapter(Context context, Cursor cursor, int collapsedGroupLayout, 
            int expandedGroupLayout, String[] groupFrom, int[] groupTo, 
            int childLayout, String[] childFrom, int[] childTo) 
public SimpleCursorTreeAdapter(Context context, Cursor cursor, int groupLayout, 
            String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, 
            int[] childTo) 
与SimpleExpandableListAdapter不同的是List<? extends Map> groupData改为Cursor cursor,共有方法都类似。 

七、            ListActivity7.1         概述 
定义 
public class ListActivity extends Activity 
包路径 
import android.app.ListActivity 
子类信息 
Context 
|___ ContextWrapper 
       |___ ContextThemeWrapper 
              |___ Activity 
                     |___ ListActivity 
继承Activity,封装一个ListView成员 
demo 
aipDemos/com.example.android.view/List1.java 
List1.java ~ List14.java 
菜单路径:API Demos/Views/Lists/ 
7.2         部分方法 
public void onContentChanged() 
public void setListAdapter(ListAdapter adapter) 
public ListAdapter getListAdapter() 
public void setSelection(int position) 
public int getSelectedItemPosition() 
public long getSelectedItemId() 
public ListView getListView() 
获取ListView对象,可以使用ListView的方法 
7.3         ExpandableListActivity 
public class ExpandableListActivity extends Activity implements 
        OnCreateContextMenuListener, 
ExpandableListView.OnChildClickListener, ExpandableListView.OnGroupCollapseListener, 
        ExpandableListView.OnGroupExpandListener 
继承Activity封装一个ExpandableListView对象 

八、            GridView8.1         概述 
定义 
public class GridView extends AbsListView 
包路径 
import android.widget.AbsListView 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsListView 
                     |___ GridView 
多行多列可垂直方向滚动,只支持先行后列垂直方向滚动的模式;不支持先列后行水平方向滚动的模式 
支持 
不支持 
1  2  3 
4  5  6 

1  4  7 
2  5 
3  6 
demo 
aipDemos/com.example.android.view/Grid1.java 
Grid1.java ~ Grid2.java 
菜单路径:API Demos/Views/Grid/ 
8.2         部分方法 
top padding 
bottom padding 
left padding 
right padding 
vertical spacing 
horizontal spacing 

void setVerticalSpacing(int verticalSpacing); 
设置垂直方向行间距 
void setHorizontalSpacing(int horizontalSpacing); 
设置水平方向列间距 
void setColumnWidth(int columnWidth); 
设置列宽 
void setNumColumns(int numColumns); 
设置列数 
void setGravity(int gravity); 
设置item对齐方式 
Gravity.TOP 
Gravity.BOTTOM 
Gravity.LEFT 
缺省 
Gravity.RIGHT 
Gravity.CENTER_VERTICAL 
Gravity.CENTER_HORIZONTAL 
Gravity.CENTER 
Gravity.FILL_VERTICAL 
Gravity.FILL_HORIZONTAL 
Gravity.FILL 
Gravity.CLIP_VERTICAL 
Gravity.CLIP_HORIZONTAL 
int getStretchMode() 
void setStretchMode(int stretchMode) 
设置填充GridView时的方式 
GridView.NO_STRETCH 
使用设置的列宽和列间距排版,无视GridView的宽度 
GridView.STRETCH_SPACING 
拉伸列间距,根据列宽、列数和GridView的宽度计算列间距。Item+Space+Item 
GridView.STRETCH_SPACING_UNIFORM 
拉伸列间距,计算方式与 
GridView.STRETCH_SPACING不同。 
Space+Item+Space+Item+Space 
GridView.STRETCH_COLUMN_WIDTH 
拉伸列宽,根据列间距、列数和GridView的宽度计算列宽。 
ListAdapter getAdapter() 
void setAdapter(ListAdapter adapter) 
设置item列表 
public void setSelection(int position) 

九、            AbsSpinner9.1         概述 
定义 
public abstract class AbsSpinner extends AdapterView 
包路径 
import android.widget.AbsSpinner; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsSpinner 
                     |___ Gallery 
                     |___ Spinner 
9.2         部分方法 
void setAdapter(SpinnerAdapter adapter) 
SpinnerAdapter getAdapter() 
void setSelection(int position, boolean animate) 
void setSelection(int position) 
int getCount() 
int pointToPosition(int x, int y) 
Parcelable onSaveInstanceState() 
void onRestoreInstanceState(Parcelable state) 

十、            Gallery10.1     概述 
定义 
public class Gallery extends AbsSpinner implements GestureDetector.OnGestureListener 
包路径 
import android.widget.Gallery; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsSpinner 
                     |___ Gallery 
items水平方向滚动显示,滚动停止时选择项停在屏幕正中。 
demo 
aipDemos/com.example.android.view/Gallery1.java 
Gallery1.java ~ Gallery2.java 
菜单路径:API Demos/Views/Gallery/ 
10.2     部分方法 
void setCallbackDuringFling(boolean shouldCallback) 
滑动过程中是否每项都调用getOnItemSelectedListener()注册的callback 
false:最后选中的一项才调用callback 
true:所有项都调用callback 
void setAnimationDuration(int animationDurationMillis) 
设置反弹回屏幕正中这部分的动画时间间隔,单位毫秒,缺省为400ms。 
void setSpacing(int spacing) 
设置两项之间的间距,缺省为0,单位象素 
void setUnselectedAlpha(float unselectedAlpha) 
设置未选中项的alpha值 0~1.0 

十一、           Spinner11.1     概述 
定义 
public class Spinner extends AbsSpinner implements OnClickListener 
包路径 
import android.widget.Spinner; 
子类信息 
View 
|___ ViewGroup 
       |___ AdapterView 
              |___ AbsSpinner 
                     |___ Spinner 
在一个单行文本框中,同时只显示一个有序列表中的一个项,点击弹出一个下拉单选对话框,从中进行选择。 
系统自带布局文件: 
simple_spinner_dropdown_item.xml 
simple_spinner_item.xml 
demo 
aipDemos/com.example.android.view/Spinner1.java 
菜单路径:API Demos/Views/Spinner/ 
11.2     部分方法 
public int getBaseline() 
public void setOnItemClickListener(OnItemClickListener l) 
抛出异常RuntimeException 
public boolean performClick() 
弹出下拉对话框 
public void onClick(DialogInterface dialog, int which) 
public void setPrompt(CharSequence prompt) 
public void setPromptId(int promptId) 
public CharSequence getPrompt() 
设置下拉菜单标题 

十二、           LinearLayout12.1     概述 
定义 
public class LinearLayout extends ViewGroup 
包路径 
import android.widget.LinearLayout; 
子类信息 
View 
|___ ViewGroup 
       |___ LinearLayout 
              |___ RadioGroup 
              |___ TabWidget 
              |___ TableLayout 
              |___ TableRow 
              |___ ZoomControls 
              |___ NumberPicker 
LinearLayout可以设置位水平的一行或垂直的一列,所有子元素按加入顺序排列,通过setOrientation()来设置行模式还是列模式,缺省为行模式。通过setGravity()设置对齐方式。 
也可以对单个子元素制定weight,允许子元素填充屏幕上的剩余空间,剩余空间安指定的比例分配。 
demo 
aipDemos/com.example.android.view/linear_layout_1.java 
linear_layout_1.java ~ linear_layout_10.java 
菜单路径:API Demos/Views/ Layouts/LinearLayout/ 
12.2     部分方法 
public LinearLayout(Context context) 
public LinearLayout(Context context, AttributeSet attrs) 
public boolean isBaselineAligned() 
public void setBaselineAligned(boolean baselineAligned) 
public int getBaseline() 
获取baseline距离顶端的距离,不支持baseline对齐返回-1 
public int getBaselineAlignedChildIndex() 
public void setBaselineAlignedChildIndex(int i) 
public float getWeightSum() 
public void setWeightSum(float weightSum) 
public void setOrientation(int orientation) 
public int getOrientation() 
HORIZONTAL:行模式 
VERTICAL:列模式 
public void setGravity(int gravity) 
public void setHorizontalGravity(int horizontalGravity) 
public void setVerticalGravity(int verticalGravity) 
对齐方式 
public LayoutParams generateLayoutParams(AttributeSet attrs) 
public static class LayoutParams extends ViewGroup.MarginLayoutParams 
增加了一个参数weight 
public LayoutParams(int width, int height, float weight) 
比如3个layout排成一行,分别为ly1, ly2, ly3 
width值分别为width1,width2,width3 
FILL_PARENT的宽度为WIDTH 
weight值分别为weight1, weight2, weight3 
只要weight1,weight2,weight3不同时为0,则3个layout总宽度变为WIDTH 
ly1的宽度为 
对weight未负数,width1+width2+width3 >= WIDTH未做测试 
12.3     LinearLayout.LayoutParams 
public static class LayoutParams extends ViewGroup.MarginLayoutParams 
public float weight;              //增加weight属性 
public int gravity = -1; 
public LayoutParams(int width, int height, float weight) 
12.4     RadioGroup 
demo 
aipDemos/com.example.android.view/RadioGroup1.java 
菜单路径:API Demos/Views/ Radio Group/ 
一列RadioButton 
public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) 
子项有变化时触发的监听器,增加/删除项 
public void check(int id) 
设置id项为选择 
public int getCheckedRadioButtonId() 
获取选择项的id 
public void clearCheck() 
清除选择状态 
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) 
RadioButton状态改变监听器 
12.5     TabWidget 
通常用作TabHost的子元素,单独使用同LinearLayout。 
12.6     TableRow 
通常用作TableLayout子元素,单独使用同LinearLayout。 
12.7     ZoomControls 
系统带布局文件 
zoom_controls.xml 
public void setOnZoomInClickListener(OnClickListener listener) 
public void setOnZoomOutClickListener(OnClickListener listener) 
public void setZoomSpeed(long speed) 
public boolean onTouchEvent(MotionEvent event) 
public void show() 
淡入 
public void hide() 
淡出消失 
public void setIsZoomInEnabled(boolean isEnabled) 
public void setIsZoomOutEnabled(boolean isEnabled) 
public boolean hasFocus() 

十三、           TableLayout13.1     概述 
定义 
public class TableLayout extends LinearLayout 
包路径 
import android.widget.TableLayout; 
子类信息 
View 
|___ ViewGroup 
       |___ LinearLayout 
              |___ TableLayout 
TableLayout将子元素的位置分配到行或列中,一个TableLayout由许多TableRow组成,每个TableRow都定义一个row,TableLayout不显示row、column或cell的边框线,每个row拥有0个或多个cell,每个cell拥有一个view对象。列可以被隐藏setColumnCollapsed(),也可以设置为伸展从而填充可利用的屏幕空间setColumnStretchable(),也可以设置为强制收缩直到表各匹配屏幕大小setColumnShrikable()。 
TableLayout宽始终为FILL_PARENT,TableRow的高始终未WRAP_CONTEN。 
demo 
aipDemos/com.example.android.view/TableLayout1.java 
TableLayout1.java ~ TableLayout12.java 
菜单路径:API Demos/Views/ Layouts/TableLayout 
13.2     部分方法 
public boolean isShrinkAllColumns() 
public void setShrinkAllColumns(boolean shrinkAllColumns) 
是否所有列可收缩 
public boolean isStretchAllColumns() 
public void setStretchAllColumns(boolean stretchAllColumns) 
是否所有列可拉伸 
public void setColumnCollapsed(int columnIndex, boolean isCollapsed) 
public boolean isColumnCollapsed(int columnIndex) 
columnIndex列是否隐藏,必须是TableRow的列才能隐藏 
public void setColumnStretchable(int columnIndex, boolean isStretchable) 
public boolean isColumnStretchable(int columnIndex) 
columnIndex列是否可拉伸 
public void setColumnShrinkable(int columnIndex, boolean isShrinkable) 
public boolean isColumnShrinkable(int columnIndex) 
columnIndex列是否可收缩 
13.3     TableLayout.LayoutParams 
public static class LayoutParams extends LinearLayout.LayoutParams 
重载了构造函数强制设width为FILL_PARENT 
13.4     TableRow.LayoutParams 
public static class LayoutParams extends LinearLayout.LayoutParams 
public int column;  //第几列 
public int span;      //占几列宽 
public LayoutParams(int column) 

十四、           FrameLayout14.1     概述 
定义 
public class FrameLayout extends ViewGroup 
包路径 
import android.widget.FrameLayout 
子类信息 
View 
|___ ViewGroup 
       |___ FrameLayout 
              |___ DatePicker 
              |___ TimePicker 
              |___ MediaController 
              |___ ScrollView 
              |___ TabHost 
              |___ ViewAnimator 
                     |___ ViewFlipper 
                     |___ ViewSwitcher 
                            |___ ImageSwitcher 
                            |___ TextSwitcher 
FrameLayout定制为屏幕上一个空白备用区域,可以在其中填充一个单一对象。所有的子元素将会固定在屏幕的左上角,不能为FrameLayout中一个子元素制定位置,后一个子元素将直接在前一个子元素之上进行覆盖填充,把他们全部或部分挡住(除非后一个子元素是透明的)。 
14.2     部分方法 
public FrameLayout(Context context) 
public FrameLayout(Context context, AttributeSet attrs) 
public FrameLayout(Context context, AttributeSet attrs, int defStyle) 
public void setForegroundGravity(int foregroundGravity) 
设置前景对齐方式,缺省为Gravity.FILL 
public Drawable getForeground() 
public void setForeground(Drawable drawable) 
设置drawable,drawable是一个可绘制的“设备”,drawable显示在所有child之上 
public void draw(Canvas canvas) 
手动把canvas所在的view显示出来,不用重载该函数,注意与onDraw(Canvas)的区别 
public boolean gatherTransparentRegion(Region region) 
public void setMeasureAllChildren(boolean measureAll) 
public boolean getConsiderGoneChildrenWhenMeasuring() 
public LayoutParams generateLayoutParams(AttributeSet attrs) 
14.3     FrameLayout. LayoutParams 
public static class LayoutParams extends MarginLayoutParams 
public int gravity = -1; 
public LayoutParams(Context c, AttributeSet attrs) 
public LayoutParams(int width, int height) 
14.4     DatePicker 
由3个NumberPicker组成,系统自带一个layout文件: 
\cupcake\frameworks\base\core\res\res\layout\date_picker.xml, 
这个缺省布局方式为水平LinearLayout,顺序为Month/Day/Year 
这个控件dayOfMont的范围校验做的还不好,比如当前时间是2009/3/31,月份减一后为2009/2/31,而这个日期是非法的,但设置为系统日期是可以成功的,结果为2009/3/3。 
demo 
aipDemos/com.example.android.view/DateWidgets1.java 
DateWidgets1.java ~ DateWidgets2.java 
菜单路径:API Demos/Views/Date Widgets/ 
public void setEnabled(boolean enabled) 
public void updateDate(int year, int monthOfYear, int dayOfMonth) 
monthOfYear:0~11 
year:1900~2100 
dayOfMonth:1~31 
public void init(int year, int monthOfYear, int dayOfMonth, 
            OnDateChangedListener onDateChangedListener) 
public void setEnabled(boolean enabled) 
public int getYear() 
public int getMonth() 
public int getDayOfMonth() 
14.5     TimePicker 
demo同上 
public void setEnabled(boolean enabled) 
public void setOnTimeChangedListener( 
OnTimeChangedListener onTimeChangedListener) 
public Integer getCurrentHour() 
public void setCurrentHour(Integer currentHour) 
public void setIs24HourView(Boolean is24HourView) 
public boolean is24HourView() 
public Integer getCurrentMinute() 
public void setCurrentMinute(Integer currentMinute) 
public int getBaseline() 
14.6     MediaController 
demo 
aipDemos/com.example.android.media/VideoViewDemo.java 
14.7     ScrollView 
demo 
aipDemos/com.example.android.view/ScrollView1.java 
ScrollView1.java ~ ScrollView2.java 
aipDemos/com.example.android.view/InternalSelectionScroll.java 
菜单路径:API Demos/Views/ Layouts/ScrollView/ 
ScrollView只支持垂直方向滚动,只能有一个子对象,这个子对象的大小可以超过屏幕大小。这个子对象不能是ListView或TextView,因这两个view是自己管理如何滚动。这个子对象通常使用LinearLayout 
public void addView(View child) 
public void addView(View child, int index) 
public void addView(View child, ViewGroup.LayoutParams params) 
public void addView(View child, int index, ViewGroup.LayoutParams params) 
只能有一个子元素,在已有一个子元素时再调用会抛出异常IllegalStateException() 
public int getMaxScrollAmount() 
public boolean isFillViewport() 
public void setFillViewport(boolean fillViewport) 
true:拉伸高度到viewport的高 
public boolean isSmoothScrollingEnabled() 
public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) 
true:滚动过程用动画过渡 
public boolean pageScroll(int direction) 
翻页 
public boolean fullScroll(int direction) 
翻到底部或顶部 
public boolean arrowScroll(int direction) 
翻项 
View.FOCUS_DOWN 
View.FOCUS_UP 
public final void smoothScrollBy(int dx, int dy) 
相对目前位置滚动(x, y) 
public final void smoothScrollTo(int x, int y) 
滚动到绝对位置(x, y) 
public void scrollTo(int x, int y) 
无动画效果滚动 
public void fling(int velocityY) 
14.8     TabHost 
demo 
aipDemos/com.example.android.view/Tabs1.java 
Tabs1.java~ Tabs3.java 
菜单路径:API Demos/Views/ Layouts/LinearLayout/ 
对应TabActivity 
TabHost由TabWidget,TabContent组成。 
TabWidget包含多个TabSpec;TabContent是FrameLayout. 
TabSpec由tag,indictor,content组成,content可以是 
1.ViewId;2.intent;3.TabHost.TabContentFactory。 
内部接口TabHost.TabContentFactory 
public interface TabContentFactory { 
View createTabContent(String tag); 

在xml文件中定义TabHost需注意两点: 
1.TabWidget的id必须指定为"@android:id/tabs",否则会有RuntimeException 
 
2.addTab()之前需调用setup()方法,继承TabActivity则不需要 
public TabSpec newTabSpec(String tag) 
创建一个tab标签,tab标签由3部分组成:tag文字,label文字/图片,content 
内部类TabHost.TabSpec,它的每个函数都返回this对象,便于链式表达,比如: 
tabHost.addTab(tabHost.newTabSpec("tab1") 
                .setIndicator("tab1") 
                .setContent(R.id.view1)); 
public class TabSpec { 
public TabSpec setIndicator(CharSequence label); 
public TabSpec setIndicator(CharSequence label, Drawable icon); 
public TabSpec setContent(int viewId); 
public TabSpec setContent(TabContentFactory contentFactory); 
public TabSpec setContent(Intent intent); 
}; 
public void setup() 
public void setup(LocalActivityManager activityGroup) 
从xml创建TabHost 才须调setup(),如果TabSpec的content是intent需调用带参数的setup() 
public void addTab(TabSpec tabSpec) 
public void clearAllTabs() 
public void setCurrentTabByTag(String tag) 
public void setCurrentTab(int index) 
public int getCurrentTab() 
public String getCurrentTabTag() 
public View getCurrentTabView() 
public View getCurrentView() 
public TabWidget getTabWidget() 
public FrameLayout getTabContentView() 
public void onTouchModeChanged(boolean isInTouchMode) 
public void setOnTabChangedListener(OnTabChangeListener l) 
标签变化触发的监听器 
14.9     ViewAnimator 
因FrameLayout是多个子元素占同样的显示区域,则在不同子元素切换显示时可以加动画效果。通常是当前显示的view消失,下一个显示的view出现。 
public void setDisplayedChild(int whichChild) 
public void setDisplayedChild(int whichChild) 
public int getDisplayedChild() 
public void showNext() 
public void showPrevious() 
public void addView(View child, int index, ViewGroup.LayoutParams params) 
重载了该方法,在加第一个view的状态为View.VISIBLE,之后加的view状态都是View.GONE 
public View getCurrentView() 
public Animation getInAnimation() 
public void setInAnimation(Animation inAnimation) 
public Animation getOutAnimation() 
public void setOutAnimation(Animation outAnimation) 
public void setInAnimation(Context context, int resourceID) 
public void setOutAnimation(Context context, int resourceID) 
public void setAnimateFirstView(boolean animate) 
14.10 ViewFlipper 
14.11 ViewSwitcher 
14.12 ImageSwitcher 
demo 
aipDemos/com.example.android.view/ImageSwitcher1.java 
菜单路径:API Demos/Views/ ImageSwitcher/ 
14.13 TextSwitcher 
demo 
aipDemos/com.example.android.view/TextSwitcher1.java 
菜单路径:API Demos/Views/ TextSwitcher/ 

十五、           RelativeLayout15.1     概述 
定义 
public class RelativeLayout extends ViewGroup 
包路径 
import android.widget.RelativeLayout; 
子类信息 
View 
|___ ViewGroup 
       |___ RelativeLayout 
              |___ DialerFilter 
              |___ TwoLineListItem 
RelativeLayout的child view位置可以用相对于其他元素或父元素的位置来描述。如果Y的位置依赖于X,则X需先于Y描述。 
需要注意的是不要循环依赖,比如RelativeLayout的高设为WRAP_CONTENT,其child设为ALIGN_PARENT_BOTTOM 
demo 
aipDemos/com.example.android.view/RelativeLayout1.java 
RelativeLayout1.java ~ RelativeLayout2.java 
菜单路径:API Demos/Views/Layouts/RelativeLayout/ 
15.2     部分方法 
public void setIgnoreGravity(int viewId) 
public void setGravity(int gravity) 
public void setHorizontalGravity(int horizontalGravity) 
public void setVerticalGravity(int verticalGravity) 
public int getBaseline() 
public LayoutParams generateLayoutParams(AttributeSet attrs) 
public static class LayoutParams extends ViewGroup.MarginLayoutParams 
LEFT_OF              位于指定child的左边 
RIGHT_OF 
ABOVE 
BELOW 
ALIGN_BASELINE      
ALIGN_LEFT                     相对指定child的左边对齐 
ALIGN_TOP 
ALIGN_RIGHT 
ALIGN_BOTTOM 
ALIGN_PARENT_LEFT 
ALIGN_PARENT_RIGHT 
ALIGN_PARENT_TOP 
ALIGN_PARENT_BOTTOM 
CENTER_IN_PARENT 
CENTER_HORIZONTAL 
CENTER_VERTICAL 
15.3     RelativeLayout.LayoutParams 
public static class LayoutParams extends ViewGroup.MarginLayoutParams 
public boolean alignWithParent;   
public LayoutParams(Context c, AttributeSet attrs) 
public LayoutParams(int w, int h) 
public LayoutParams(ViewGroup.LayoutParams source) 
public LayoutParams(ViewGroup.MarginLayoutParams source) 
public void addRule(int verb) 
只用于添加相对于parent的规则,可用addRule(verb, RelativeLayout.TRUE)代替,RelativeLayout.TRUE的值为-1 
public void addRule(int verb, int anchor) 
verb为相对于兄弟位置,则anchor必须为有效的兄弟id设置才生效,否则无效 
verb为相对于parent位置,anchor无论设为何值都生效 
public int[] getRules() 
15.4     DialerFilter 
15.5     TwoLineListItem 

十六、           AbsoluteLayout16.1     概述 
定义 
public class AbsoluteLayout extends ViewGroup 
包路径 
import android.widget.Absolutelayout; 
子类信息 
View 
|___ ViewGroup 
       |___ AbsoluteLayout 
              |___ WebView 
AbsoluteLayout可以对其子元素指定准确的x/y坐标值,允许元素之间相互重叠,不推荐使用。 
16.2     部分方法 
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) 
16.3     AbsoluteLayout. LayoutParams 
public static class LayoutParams extends ViewGroup.LayoutParams 
public int x;    // 在ViewGroup.LayoutParams基础上增加坐标(x, y) 
public int y; 
public LayoutParams(int width, int height, int x, int y) 
public LayoutParams(Context c, AttributeSet attrs) 
public LayoutParams(ViewGroup.LayoutParams source) 

十七、           WebView17.1     概述 
定义 
public class WebView extends AbsoluteLayout 
        implements ViewTreeObserver.OnGlobalFocusChangeListener, 
        ViewGroup.OnHierarchyChangeListener 
包路径 
import android.webkit.WebView; 
子类信息 
View 
|___ ViewGroup 
       |___ AbsoluteLayout 
              |___ WebView 
WebView用于显示网页,用于可滚动显示的web浏览器或简单显示在线内容的Activity。用WebKit显示网页和在历史记录向前向后操作、放大缩小、搜索文字 
 
demo 
aipDemos/com.example.android.view/webview_1.java 
菜单路径:API Demos/Views/WebView/ 
17.2     部分方法 
public void clearCache(boolean includeDiskFiles) 
public void goBack() 
public void goForward() 
public String getUrl() 
public String getTitle() 
public void reload() 
public void loadUrl(String url) 
public boolean zoomIn() 
public boolean zoomOut() 
public void goBackOrForward(int steps)



在网站上搜索的时候看到了windowManager、window、viewGroup中的实现原理,看了一下,觉得不错所以一并贴到这里来了。

介绍addview方法,在windowManager、window、viewGroup中的实现原理。首先将介绍这些类结构关系,然后分析其内在联系,介绍实现原理,最后介绍重要的一个参数windowManager.layoutParams。

文章预计分为三个部分。
一、首先介绍一下上述接口、类的结构

  接口:windowManager

    用来在应用与window之间的管理接口,管理窗口顺序,消息等


public interface WindowManager extends android.view.ViewManager

     抽象类:window

    定义窗口样式和行为的抽象基类,用于作为顶层的view加到windowManager中。

    唯一实现了这个抽象类的是PhoneWindow,实例化PhoneWindow需要一个窗口

    public abstract class Window

    其中有一个很重要的内部类

    private class LocalWindowManager extends WindowManagerImpl.CompatModeWrapper{...};

  

  抽象类:viewGroup

    包含其他view的容器,layouts和view 容器的基类。

    public abstract class ViewGroup extends View implements ViewParent, ViewManager

  

  相关接口:ViewParent

        定义了一个view parent 的要负责的功能以及view和parent view之间的关联

    public interface ViewParent {

         public void requestLayout();

        public void createContextMenu(ContextMenu menu);

        public void bringChildToFront(View child);

        .....

    }

    viewManager

      用来添加和移除activity中的view的接口

public interface ViewManager
{
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}



二.他们之间的内在关系。

  1. 对于view来说,添加到viewGroup中是通过addView();方式来实现的,在addView中实际上使用的是:

            addViewInner(child, index, params, false);

           流程是: 1.首先是对子View是否已经包含到一个父容器中

                2.对子View布局参数的处理

                3.调用addInArray来添加View

                4.设置父View为当前的ViewGroup

                5.焦点的处理

                6.当前View的AttachInfo信息

                7.View树改变的监听

                8.子View中的mViewFlags的设置

                             主要是通过    addInArray添加view,添加的实现为system.arrayCopy(....);

  

  2. 对于viewGroup来说,都会显示在在一个窗口中,每个都有一个父节点mParent,,最顶上的节点也是一个viewGroup,也就是decorView。

  对于每个activity只有一个decorView也就是ViewRoot,只有一个window,window的获取是通过下面方法获取的。

  1. Window mWindow = PolicyManager.makeNewWindow(this);
复制代码 在activity中使用setContentView(),其实是使用了 window.setContentView()完成的,window.setcontentView,

  还是通过LocalWindowManager.addView(view, params)来实现的。这里LocalWindowManager是实现了WindowManagerImpl.CompatModeWrapper

  ,本质上就是WindowManager、viewManager接口中的addvidew方法。

  

  3.  对于windowManager来说一个系统只有一个,它是由系统底层实现的,用于负责调度当前显示那个窗口,消息处理我们获得一个windowManager的方式如下:

  1. WindowManager windowManager = (WindowManager)context().getSystemService(

  2.                                     Context.WINDOW_SERVICE);
复制代码 这里windowManager其实是一个接口,而通过getSystemService的方式。通过这个方式可以获取很多的系统服务,比如电话、闹钟、电源管理等等。

  同时windowManager和几个类之间的内在联系如下:

windowManager类图关系.jpg (67.46 KB, 下载次数: 0)

下载附件  保存到相册

2013-10-10 19:02 上传






更多相关文章

  1. Android studio生成APK打包,修改生成APK的路径和名字
  2. android SDK系统图片资源的路径。
  3. 2011.09.09 ——— android 2.2 修改安装路径
  4. 更改Android AVD模拟器创建路径位置的方法
  5. android 窗口如何靠左和靠右边框布局
  6. Android用户界面 UI组件--ImageView及其子类ImageButton,QuickCo
  7. Android用户界面 UI组件--AdapterView及其子类(二) AdapterViewA
  8. Android 存储路径浅析

随机推荐

  1. Android中因为没有使用wifi模块 因此:将WI
  2. Android(安卓)开源项目分类汇总
  3. Android(安卓)IntentService问题
  4. android弹出框2(相当于通知)
  5. Java編程和Android編程的區別
  6. Android(安卓)多线程注意事项
  7. Android(安卓)adb setuid提权漏洞的分析
  8. android 线程间通信
  9. android短彩信数据库设计(三)
  10. Android(安卓)API 中文 (54) —— Filterab