[英]how to set layout_margin for a view (not for a viewGroup) programmatically in android
在为GridLayout
动态创建的ImageView
以编程方式设置layout_margin
时,我遇到了问题。 我试过以下代码:
GridLayout gridLayout = (GridLayout) findViewById(R.id.idGridLayout);
gridLayout.setColumnCount(10);
gridLayout.setRowCount(10);
for (int i = 1; i <= 100; i++) {
ImageView tile1 = new ImageView();
LayoutParams lp = new LayoutParams(100, 100);
tile1.setLayoutParams(lp);
lp.setMargins(4, 4, 4, 4); ////not working some error
tile1.setBackgroundColor(Color.rgb(255, 255, 5));
//tile1.setBackgroundResource(R.drawable.aalien);
//tile1.setBackgroundColor();
我找到了一个方法setMargins(4, 4, 4, 4)
,但是通过这种方式,我只能为诸如LinearLayout
/ GridLayout
/ RelativeLayout
等的ViewGroups
设置边距。
但是我想像使用android:layout_margin="5dp"
在xml
那样为ImageView
设置边距
尝试对每个ImageView
执行此操作
ImageView imageView = new ImageView(context);
GridLayout.LayoutParams params = (GridLayout.LayoutParams) imageView.getLayoutParams();
params.setMargins(4, 4, 4, 4); // left, top, right, bottom
imageView.setLayoutParams(params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.