如何以编程方式使用一个在另一个按钮上的两个按钮来创建RelativeLayout? [英] How to create a RelativeLayout programmatically with two buttons one on top of the other?

查看:94
本文介绍了如何以编程方式使用一个在另一个按钮上的两个按钮来创建RelativeLayout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UI中添加了两个按钮,但它们彼此重叠显示.我希望它们彼此相邻出现.我在这段代码中缺少什么?

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);

推荐答案

我们应该使用setId()显式设置id.只有这样,RIGHT_OF规则才有意义.

We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.

我犯的另一个错误是在控件之间重用layoutparams对象.我们应该为每个控件创建一个新对象

Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control

这篇关于如何以编程方式使用一个在另一个按钮上的两个按钮来创建RelativeLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆