一般常用的是在布局文件中设置margin属性,如:
但是实际需求中,时常需要在代码里来控制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();
}
}
}