android在代码中设置margin属性

xiaoxiao2021-02-28  5

一般常用的是在布局文件中设置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布局里面。 效果图:

方式二 RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(100, 100, 0, 0);//4个参数按顺序分别是左上右下 tv.setLayoutParams(lp);

效果图:

方式三 RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT); lp.setMargins(100, 100, 0, 0);//4个参数按顺序分别是左上右下 tv.setLayoutParams(lp);

效果图:

之前看到别人把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(); } } }
转载请注明原文地址: https://www.6miu.com/read-2400205.html

最新回复(0)