android在代码中设置margin属性

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RELY_ON_YOURSELF/article/details/79139013

一般常用的是在布局文件中设置margin属性,如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_marginLeft="20dp"
        android:id="@+id/tv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#789456"
        android:gravity="center"
        android:text="黑暗森林" />

</RelativeLayout>

但是实际需求中,时常需要在代码里来控制view的margin属性,可是view中有setPadding()方法 , 却没有setMargin()方法,应该如何处理呢?

通过查阅android api,可以发现android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom).其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

可以通过设置view里面的 LayoutParams 设置,而这个LayoutParams是根据该view在不同的GroupView而不同的。

   RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(tv.getLayoutParams());

   lp.setMargins(100, 100, 0, 0);

   tv.setLayoutParams(lp);

这里的RelativeLayout是说明该view在一个RelativeLayout布局里面。

之前看到别人把setMargin封装成方法 , 比较好 , 这里借鉴一下 . 只要是GroupView直接的子类就行 , 即: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams. 。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv = findViewById(R.id.tv);

        margin(tv,100, 100, 0, 0);

//        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(tv.getLayoutParams());
//
//        lp.setMargins(100, 100, 0, 0);
//
//        tv.setLayoutParams(lp);


    }

    public void margin(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

} 

猜你喜欢

转载自blog.csdn.net/RELY_ON_YOURSELF/article/details/79139013