簡體   English   中英

以編程方式更改視圖邊距

[英]Change a view margins programmatically

所以我有一個具有 250dp 底部邊距的 RecyclerView 我需要以編程方式將底部邊距設置為 0dp,然后將其設置回 250dp,我已經嘗試過了,但它只是將其設置為 0dp 並且將其設置為 250dp 不起作用背部:

    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) linearLayoutRv.getLayoutParams();
                params.setMargins(0,0,0,250); // params.setMargins(0,0,0,0); at first
                linearLayoutRv.setLayoutParams(params);

有一些不必要的東西,但這里是 xml 文件:

    <androidx.constraintlayout.widget.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/linearLayoutRv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="250dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="51dp"
            android:gravity="center">
            //textview
          
        </androidx.constraintlayout.widget.ConstraintLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="51dp"
            android:orientation="horizontal">
            //some buttons
        </LinearLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginHorizontal="5dp"
            android:padding="4dp"
            android:scrollbars="vertical" />
    </LinearLayout>

問題是setMargins接受的值不是以dp (密度獨立像素)為單位,而是以px (像素)為單位。

在將其傳遞給params object 之前,您必須將值 250 轉換為dp

Context context = ...; // place 'this' if you are in an Activity or 'requireContext()' if you are in a Fragment
Resources res = context.getResources();
float dp250 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, res.getDisplayMetrics());

ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) linearLayoutRv.getLayoutParams();
params.setMargins(0, 0, 0, dp250);
linearLayoutRv.setLayoutParams(params);

dp250將導致不同設備上的像素數不同。 這取決於分辨率和物理屏幕尺寸。

當您以編程方式設置邊距時,您以像素為單位設置值,而不是 dp。 LayoutParams 的來源:

         /**
         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
         * to be done so that the new margins are taken into account. Left and right margins may be
         * overridden by {@link android.view.View#requestLayout()} depending on layout direction.
         * Margin values should be positive.
         *
         * @param left the left margin size
         * @param top the top margin size
         * @param right the right margin size
         * @param bottom the bottom margin size
         *
         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
         */
        public void setMargins(int left, int top, int right, int bottom) {
            leftMargin = left;
            topMargin = top;
            rightMargin = right;
            bottomMargin = bottom;
            mMarginFlags &= ~LEFT_MARGIN_UNDEFINED_MASK;
            mMarginFlags &= ~RIGHT_MARGIN_UNDEFINED_MASK;
            if (isMarginRelative()) {
                mMarginFlags |= NEED_RESOLUTION_MASK;
            } else {
                mMarginFlags &= ~NEED_RESOLUTION_MASK;
            }
        }

您需要將 dp 轉換為像素:

Int yourDP = 250
Resources r = getResources();
float px = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    yourDP,
    r.getDisplayMetrics()
);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) linearLayoutRv.getLayoutParams();
            params.setMargins(0,0,0,(int) px); // params.setMargins(0,0,0,0); at first
            linearLayoutRv.setLayoutParams(params);

您可以使用MotionLayout輕松做到這一點。 只需將父ConstraintLayout轉換為MotionLayout ,創建MotionScene並在代碼中使用transitionToEnd()transitionToStart()

例子

它可以工作,但以像素為單位,所以我添加了這個方法:

public static int convertDpToPixel(int dp, Context context){
    return dp * ((int) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

並改變了這一點:

params.setMargins(0,0,0,convertDpToPixel(250,getContext()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM