我们平常可以直接在xml里设置margin,如:

<ImageView android:layout_margin="5dip" android:src="@drawable/image" />

但是有些情况下,需要在java代码里来写,可是View本身没有setMargin方法,怎么办呢?

 

通过查阅android api,我们发现android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom).

其直接的子类有: FrameLayout.LayoutParams,

        LinearLayout.LayoutParams,

        RelativeLayout.LayoutParams.

 使用方法:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 20, 30, 40);
imageView.setLayoutParams(lp);

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
  • 2021-06-29
  • 2021-05-05
  • 2022-12-23
猜你喜欢
  • 2021-10-11
  • 2021-07-22
  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案