首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在android中以编程方式设置视图的layout_margin (而不是viewGroup)

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

Stack Overflow用户
提问于 2016-03-31 20:09:44
回答 1查看 271关注 0票数 1

在为动态创建的layout_marginGridLayout中以编程方式设置GridLayout时,我面临着问题。我尝试了以下代码:

代码语言:javascript
运行
复制
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),但是通过这个方法,我只能为像setMargins(4, 4, 4, 4)这样的ViewGroups设置页边距。

但是,我想为ImageView设置页边距,就像在xml中使用android:layout_margin="5dp"那样

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-31 20:24:58

尝试为每个ImageView执行此操作

代码语言:javascript
运行
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36342805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档