사용자 정의 View-2 - 다시 쓰기 onMeasure

4738 단어

효과도


레이아웃 파일

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView  android:layout_width="match_parent" android:layout_height="100dp" android:background="#003839" android:gravity="center" android:visibility="visible" android:text="SECOND"/>

    <com.pengkv.apple.weight.FirstView  android:layout_width="wrap_content" android:visibility="visible" android:background="#888787" android:layout_height="wrap_content"/>

</LinearLayout>

View 코드

public class FirstView extends LinearLayout {

    public FirstView(Context context) {//          
        super(context);
    }

    public FirstView(Context context, AttributeSet attrs) {//           
        super(context, attrs);
    }

    public FirstView(Context context, AttributeSet attrs, int defStyleAttr) {//           
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        setMeasuredDimension(measureSpec(widthMeasureSpec),measureSpec(heightMeasureSpec)); //    
    }

    public int measureSpec(int measureSpec){
        int result=0;
        int specMode=MeasureSpec.getMode(measureSpec);//      
        int specSize=MeasureSpec.getSize(measureSpec);//      

        if (specMode==MeasureSpec.EXACTLY){//    :      dp  match_parent
            result=specSize;
        }else {
            result=400;//       
            if (specMode==MeasureSpec.AT_MOST){
                result=Math.min(result,specSize);
            }
        }
        return result;
    }
}

좋은 웹페이지 즐겨찾기