效果图
布局文件
>
<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; }}