Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 解析:繼承ViewGroup後的子類如何重寫onMeasure方法

解析:繼承ViewGroup後的子類如何重寫onMeasure方法

編輯:關於Android編程

1.首先貼上我試驗成功的代碼
復制代碼 代碼如下:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

         int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
         int measureHeigth = MeasureSpec.getSize(heightMeasureSpec);
         setMeasuredDimension(measureWidth, measureHeigth);
         // TODO Auto-generated method stub
         for(int i= 0;i<getChildCount();i++){
             View v = getChildAt(i);
             Log.v(TAG, "measureWidth is " +v.getMeasuredWidth() + "measureHeight is "+v.getMeasuredHeight());
             int widthSpec = 0;
             int heightSpec = 0;
             LayoutParams params = v.getLayoutParams();
             if(params.width > 0){
                 widthSpec = MeasureSpec.makeMeasureSpec(params.width, MeasureSpec.EXACTLY);
             }else if (params.width == -1) {
                 widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.EXACTLY);
             } else if (params.width == -2) {
                 widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.AT_MOST);
             }

             if(params.height > 0){
                 heightSpec = MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY);
             }else if (params.height == -1) {
                 heightSpec = MeasureSpec.makeMeasureSpec(measureHeigth, MeasureSpec.EXACTLY);
             } else if (params.height == -2) {
                 heightSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.AT_MOST);
             }
             v.measure(widthSpec, heightSpec);

         }
     }

解釋一下:
首先判斷params.width的值是多少,有三種情況。
如果是大於零的話,及傳遞的就是一個具體的值,那麼,構造MeasupreSpec的時候可以直接用EXACTLY。
如果為-1的話,就是MatchParent的情況,那麼,獲得父View的寬度,再用EXACTLY來構造MeasureSpec。
如果為-2的話,就是wrapContent的情況,那麼,構造MeasureSpec的話直接用一個負數就可以了。
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved