习惯了直接在xml里设置margin(距离上下左右都是10dip),如:

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

只是有些情况下,需要在java代码里来写。

API中,android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom)。可是View本身没有setMargin方法,怎么办呢?

看见API上,其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams。我们我们可以这样写:

 

ImageView imageView = = new ImageView(getContext());

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);  // , 1是可选写的
lp.setMargins(10, 20, 30, 40); 
imageView.setLayoutParams(lp); 

相关文章:

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