생활
onMeasure로 부모 뷰 높이의 일정 비율을 차지하게 하기
커스텀 뷰를 ViewPager에서 쓰고 있습니다.
<?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"> <com.example.test.LinearLayout android:background="@color/background" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/above" android:tag="13/24"> </com.example.test.LinearLayout> <LinearLayout android:background="@color/colorPrimary" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> </LinearLayout>com.example.test.LinearLayout이 그 커스텀뷰인데요,
스크롤에 따라 높이와 배경에 애니메이션을 적용하기 위해 커스텀뷰를 사용했습니다.
package com.example.test; import android.content.Context; import android.util.AttributeSet; import android.support.annotation.Nullable; public class LinearLayout extends android.widget.LinearLayout { public final float ratio; private float getRatio() { String tmp[] = getTag().toString().split("/"); return Integer.parseInt(tmp[0]) / Float.parseFloat(tmp[1]); } public LinearLayout(Context context) { super(context); ratio = getRatio(); } public LinearLayout(Context context, @Nullable AttributeSet attrs) { super(context, attrs); ratio = getRatio(); } public LinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); ratio = getRatio(); } private android.widget.LinearLayout.LayoutParams lp = new android.widget.LinearLayout.LayoutParams(0, 0); @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { lp.width = MeasureSpec.getSize(widthMeasureSpec); lp.height = (int)(ratio * MeasureSpec.getSize(heightMeasureSpec)); this.setMeasuredDimension(lp.width, lp.height); this.setLayoutParams(lp); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }위의 XML처럼 다른 LinearLayout 하나, 이 뷰 하나만 있는 경우만 고려해도 됩니다.
화면에서 높이를 onMeasure로 XML에서 android:tag로 설정한 비율만큼 차지하게 하려는데
앱을 처음 켰을 때부터 원하는 비율의 높이가 나오지 않습니다.
심지어 스크롤을 넘길 때마다 높이가 점점 낮아지다가 사라집니다.
어떤 부분이 잘못된 걸까요?
1개의 답변이 있어요!