Android

[Android] ScrollView maxHeight fix

yenne 2019. 8. 12. 16:15

아래와 같은 코드에,

ScrollView에 maxHeight속성을 주거나,

ScrollView의 하위 레벨 LinearLayout에 maxHeight를 아무리 주어도 고정이 되지 않았다.

 

    <ScrollView
        android:id="@+id/svBankList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/llBankList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RecyclerView
                android:id="@+id/rvBankList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </ScrollView>

 

 

그래서 찾은 방법은,

레이아웃은 위와 같이 그대로 진행하되 코드 상에 아래 내용을 넣는다.

나의 경우에는 maxHeight를 170dp로 고정했다. px과 dp에 유의하여 값을 집어 넣을 것.

        mSvBankList.measure(0, 0);
        if (mLlBankList.getMeasuredHeight() > ScreenUtils.dpToPx(getContext(), 170)) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, (int) ScreenUtils.dpToPx(getContext(), 170));
            mSvBankList.setLayoutParams(lp);
        }

 

* 참고 - dp와 px 변환 함수

public static float dpToPx(Context context, float dp) {
    if (context == null) {
        return -1;
    }
    return dp * context.getResources().getDisplayMetrics().density;
}
    
    
public static float pxToDp(Context context, float px) {
     if (context == null) {
         return -1;
     }
     return px / context.getResources().getDisplayMetrics().density;
}