【问题标题】:Android: Setting a button size programaticallyAndroid:以编程方式设置按钮大小
【发布时间】:2015-01-09 19:52:21
【问题描述】:

我正在尝试制作一个 100x100 像素的按钮并将其添加到位置 3,3 的网格布局中

Button btn = new Button(this);
btn.setLayoutParams(new ViewGroup.LayoutParams(100,100));
GridLayout grid4x4 = (GridLayout)findViewById(R.id.grid4x4);

//I've narrowed it down to the conclusion that this line is the problem:
grid4x4.addView(btn,new GridLayout.LayoutParams(GridLayout.spec(3),GridLayout.spec(3)));
//if i just use:
//grid4x4.addView(btn); I get the button the size I want it, but I need it to be on 
//the 3,3 position of the grid.

这个“几乎”有效,除了添加的按钮大于 100x100 像素这一事实,正如您所见,我正在尝试修复我想要的尺寸,但由于某种原因这不是我得到的尺寸。

【问题讨论】:

    标签: android button android-studio size layoutparams


    【解决方案1】:

    在您的res/values/dimens.xml 中添加<dimen name="mybuttonsize">100px</dimen>

    int size = (int) getResources().getDimension(R.dimen.mybuttonsize);
    

    将您的代码更改为:

    btn.setMaxWidth(size);
    btn.setMaxHeight(size);
    btn.setLayoutParams(new ViewGroup.LayoutParams(size,size));
    

    【讨论】:

    • 完全相同的结果,根据文档,公共 LayoutParams 构造函数已经将 int 作为 px 所以即使我期望它会是相同的,我尝试过并且它确实给了我相同的结果。
    • 如果我在 xml 中使用 100dp,按钮确实会变大,但如果我将它设置为 50dp,这将相当于 100px(在屏幕上即时测试)它仍然不起作用。我确实知道它可以是一个 100x100 像素的按钮,因为我已经有另一个没有以编程方式添加的按钮,它正确地显示了我想要的方式。
    【解决方案2】:

    这可能不是理想的解决方案,但这正是我想要的方式:

    Button btn = new Button(this);
    btn.setLayoutParams(new ViewGroup.LayoutParams(100,100));
    GridLayout grid4x4 = (GridLayout)findViewById(R.id.grid4x4);
    grid4x4.addView(btn);
    ((GridLayout.LayoutParams) btn.getLayoutParams()).rowSpec = GridLayout.spec(3);
    ((GridLayout.LayoutParams) btn.getLayoutParams()).columnSpec = GridLayout.spec(3);
    

    哎哟~

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2014-09-03
      • 1970-01-01
      相关资源
      最近更新 更多