Android,以编程方式布局按钮视图?
我正在尝试以编程方式定义我的程序布局并在某个位置添加一个按钮。我没有使用布局 xml 作为内容视图。
RelativeLayout mainLayout;
mainLayout = new RelativeLayout(this);
mainLayout.setLayoutParams(new
LayoutParams(LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
然后我添加了一个我想应用属性的按钮,
layout align center
parent align left
height 60px
width 60px
到目前为止,该按钮的
Button BtnNext = new Button(this);
BtnNext.setWidth(60);
BtnNext.setHeight(60);
BtnNext.setFocusable(true);
BtnNext.setId(idBtnNext);
BtnNext.setText("Next");
mainLayout.addView(BtnNext, 1);
高度和宽度无法正常工作。
I am trying to programmatically define my program layout and add a button to it at a certain position. I am not using the layout xml as the content view.
RelativeLayout mainLayout;
mainLayout = new RelativeLayout(this);
mainLayout.setLayoutParams(new
LayoutParams(LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
I have then added a button that I want to apply the properties
layout align center
parent align left
height 60px
width 60px
here is the button so far
Button BtnNext = new Button(this);
BtnNext.setWidth(60);
BtnNext.setHeight(60);
BtnNext.setFocusable(true);
BtnNext.setId(idBtnNext);
BtnNext.setText("Next");
mainLayout.addView(BtnNext, 1);
Height and width DON'T work correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您好,您可以尝试通过设置布局参数
您还可以通过设置相对布局参数来添加规则并设置按钮的边距,例如
Hi you can try by setting layout params
You can also add rules and set margins for Button by setting relative layout params like
高度和宽度不会如您所愿,因为您没有使用与密度无关的像素(dip)
您在此处设置的值以像素为单位
您可以将像素转换为倾角
最终浮点比例= getResources().getDisplayMetrics().密度;
int 倾角 = (int) (60 * 刻度 + 0.5f);
您将得到更准确的结果
Height and width will not be as u wished because your are not using Density-independent pixel (dip)
The value you set here is in pixel
You can convert the pixel into dip by
final float scale = getResources().getDisplayMetrics().density;
int dip = (int) (60 * scale + 0.5f);
You will get more accurate result