如何在android中以编程方式为视图(不是viewGroup)设置layout_margin

时间:2016-03-31 20:09:45

标签: android android-layout android-xml

layout_margin内为动态创建的ImageView以编程方式设置GridLayout时,我遇到了问题。 我试过以下代码:

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),但是我可以为ViewGroups / LinearLayout / GridLayoutRelativeLayout设置保证金。

但我希望使用ImageView

xml设置android:layout_margin="5dp"的保证金。

1 个答案:

答案 0 :(得分:0)

尝试为每个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);