编程创建于Android的一个RelativeLayout的

编程创建于Android的一个RelativeLayout的

本文介绍了编程创建于Android的一个RelativeLayout的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加入两个按钮的UI中,但它们出现在彼此的顶部。我希望他们能够彼此相邻出现。那我在这code失踪?

  m_btnCrown =新的ImageButton(本);
m_btnCrown.setImageResource(R.drawable.king_crown_thumb);
m_btnCrown.setAlpha(100);

RelativeLayout.LayoutParams LP =新RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);


addContentView(m_btnCrown,LP);


m_btnMonkey =新的ImageButton(本);
m_btnMonkey.setImageResource(R.drawable.monkey_small);
m_btnMonkey.setAlpha(100);

LP =新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);
 

解决方案

在找到Laying在RelativeLayout的意见编程

我们应该使用SETID明确设定的ID()。只有这样,RIGHT_OF规则是有意义的。

另外一个错误,我所做的是,重用控件之间的LayoutParams对象。我们应该为每个控件创建新的对象。

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);
解决方案

Found the answer in Laying 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

这篇关于编程创建于Android的一个RelativeLayout的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:39