如何以编程方式创建一个具有两个按钮一个在另一个之上的相对布局?
我正在向 UI 添加两个按钮,但它们显示在另一个按钮之上。我希望他们出现在彼此旁边。这段代码中我缺少什么?
m_btnCrown = new ImageButton(this);
m_btnCrown.setImageResource(R.drawable.king_crown_thumb);
m_btnCrown.setAlpha(100);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
addContentView(m_btnCrown, lp);
m_btnMonkey = new ImageButton(this);
m_btnMonkey.setImageResource(R.drawable.monkey_small);
m_btnMonkey.setAlpha(100);
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.addRule(RelativeLayout.RIGHT_OF, m_btnCrown.getId());
addContentView(m_btnMonkey, lp);
I'm adding two buttons to the UI, but they appear on top of one another. I want them to appear next to each other. What am I missing in this code?
m_btnCrown = new ImageButton(this);
m_btnCrown.setImageResource(R.drawable.king_crown_thumb);
m_btnCrown.setAlpha(100);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
addContentView(m_btnCrown, lp);
m_btnMonkey = new ImageButton(this);
m_btnMonkey.setImageResource(R.drawable.monkey_small);
m_btnMonkey.setAlpha(100);
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.addRule(RelativeLayout.RIGHT_OF, m_btnCrown.getId());
addContentView(m_btnMonkey, lp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我编写了一个快速示例来演示如何以编程方式创建布局。
理论上,一切都应该在评论时很清楚。如果你不明白什么就告诉我。
I have written a quick example to demonstrate how to create a layout programmatically.
In theory everything should be clear as it is commented. If you don't understand something just tell me.
在如何以编程方式在RelativeLayout中布局视图?
我们应该使用 setId() 显式设置 id。只有这样,RIGHT_OF 规则才有意义。
我犯的另一个错误是在控件之间重用layoutparams对象。我们应该为每个控件创建新对象
Found the answer in How to lay out Views in RelativeLayout programmatically?
We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.
Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control