ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 低调看直播体育app软件下载 >> Android开发 >> Android开发之自定义控件二---onLayout详解

Android开发之自定义控件二---onLayout详解(5/7)

来源:网络整理     时间:2016-01-26     关键词:

本篇文章主要介绍了"Android开发之自定义控件二---onLayout详解",主要涉及到方面的内容,对于Android开发感兴趣的同学可以参考一下: 话说一个乞丐在看一个程序员写程序,程序员遇到一个问题怎么都解决不了,这时乞丐说这少个分号,程序员照做结果问题解决了,就问:你怎么知道?乞丐笑笑说:我之前就是干这...

  1. package com.example.customviewpractice;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.util.AttributeSet;  
  6. import android.util.DisplayMetrics;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9.   
  10. public class MyViewGroup extends ViewGroup {  
  11.   
  12.     private Context mContext;  
  13.     private int sreenH;  
  14.   
  15.     public MyViewGroup(Context context, AttributeSet attrs) {  
  16.         super(context, attrs);  
  17.         mContext = context;  
  18.         // 获取屏幕的高度  
  19.         sreenH = getScreenSize(((Activity) mContext))[1];  
  20.     }  
  21.   
  22.     @Override  
  23.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  24.   
  25.         super.onMeasure(widthMeasureSpec, widthMeasureSpec);  
  26.         // 测量子View  
  27.         measureChildren(widthMeasureSpec, heightMeasureSpec);  
  28.     }  
  29.   
  30.     @Override  
  31.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  32.         // 获得子View个数  
  33.         int childCount = getChildCount();  
  34.         // 设置一个变量保存到父View左侧的距离  
  35.         int mLeft = 0;  
  36.         // 遍历子View  
  37.         for (int i = 0; i < childCount; i++) {  
  38.   
  39.             View childView = getChildAt(i);  
  40.             // 获得子View的高度  
  41.             int childViewHeight = childView.getMeasuredHeight();  
  42.             // 获得子View的宽度  
  43.             int childViewWidth = childView.getMeasuredWidth();  
  44.             // 让子View在竖直方向上显示在屏幕的中间位置  
  45.             int height = sreenH / 2 - childViewHeight / 2;  
  46.             // 调用layout给每一个子View设定位置mLeft,mTop,mRight,mBottom.左上右下  
  47.             childView.layout(mLeft, height, mLeft + childViewWidth, height  
  48.                     + childViewHeight);  
  49.             // 改变下一个子View到父View左侧的距离  
  50.             mLeft += childViewWidth;  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.      * 获取屏幕尺寸 
  56.      */  
  57.     public static int[] getScreenSize(Activity activity) {  
  58.         DisplayMetrics metrics = new DisplayMetrics();  
  59.         activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);  
  60.         return new int[] { metrics.widthPixels, metrics.heightPixels };  
  61.     }  
  62. }  
布局文件

[html] view plain copy

相关图片

相关文章