2 baby bonnie Baby_Bonnie 于 2012.10.23 14:35 提问

在Android中以编程方式创建一个RelativeLayout

我添加两个按钮到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);

2个回答

znl_12
znl_12   2012.10.23 17:01
已采纳

我写了一个简单的例子来演示如何以编程方式创建一个布局:
public class CodeLayout extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // 创建一个新的RelativeLayout
    RelativeLayout relativeLayout = new RelativeLayout(this);

    // 定义RelativeLayout布局属性  
    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.FILL_PARENT);

    // 创建一个新的TextView
    TextView tv = new TextView(this);
    tv.setText("Test");

    // 定义TextView里的布局属性
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT);

    //设置 TextView的属性 
    tv.setLayoutParams(lp);

    relativeLayout.addView(tv);

    setContentView(relativeLayout, rlp);
}

}

ueryueryuery
ueryueryuery   2012.10.26 14:06

LZ你需要的是

lp.addRule(RelativeLayout.RIGHT_OF, btnCrown的id);

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!