Android 如何在xmL 里面动态设置padding

如题,Android 如何在xmL 里面动态设置padding

有时候,你的布局加载完成之后,你findViewByid 找到控件,设置padding 会导致白条,布局闪动,那怎么办呢?

你是不是就想,在xml里面就设置好padding?

但是,Android 直接是不支持的。
只能迂回一下。我们思路就是,把一个自定义view 扔到xml 里面,自定义view 里面 动态获取你的padding值。

实现:
1。自定义view

public class DiffScreenPadding extends View {

    public DiffScreenPadding(Context context) {
        super(context);
        init();
    }

    public DiffScreenPadding(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public DiffScreenPadding(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();

    }

    private void init() {
        setBackgroundColor(Color.BLACK);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), DiffShapeScreenUtil.getPaddingArray()[1]);
    }
}

其中,DiffShapeScreenUtil.getPaddingArray()[1] 就是你自定义的高度。这个是可以变化的。代码里面,你想怎么样,还不是你说了算?这个值,你可以根据不同的情况,返回不同的值。

2。xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/layout_cartoon_browser">

    <com.weibo.xxx..View.DiffScreenPadding
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/diff_screen_padding"
        />
    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/diff_screen_padding"
        >
        <include layout="@layout/bookview_menu" android:visibility="gone"/>

    </FrameLayout>



</RelativeLayout>

然后写到xml 里面。

大功告成。重要的不是技术含量,而是思路。
你能想出来这条路吗?

原文地址:https://www.cnblogs.com/caoxinyu/p/10568566.html