如何动态地添加视图在XML布局已经宣布RelativeLayou

如何动态地添加视图在XML布局已经宣布RelativeLayou

本文介绍了如何动态地添加视图在XML布局已经宣布RelativeLayout的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个XML布局文件中声明一个 RelativeLayout的。现在,我想补充浏览从code到现有的布局。我添加了一个按钮动态以如下,现有布局到code:

I declared a RelativeLayout in a xml layout file. Now I want to add Views from code to the existing Layout. I added a Button dynamically to this existing layout as below through code:

rLayout = (RelativeLayout)findViewById(R.id.rlayout);
        LayoutParams lprams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        Button tv1 = new Button(this);
        tv1.setText("Hello");
        tv1.setLayoutParams(lprams);
        tv1.setId(1);
        rLayout.addView(tv1);

现在我需要添加另一个按钮到已经添加按钮的权利。我无法找到我在其中可以添加新的previously添加按钮右侧的方式。

Now I need to add another Button to the right of the already added Button. I am not able to find the way in which I can add the new one to the right of the previously added button.

推荐答案

添加规则 RelativeLayout.RIGHT_OF 第二添加按钮 的LayoutParams

    // first Button
    RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.rlayout);
    RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Button tv1 = new Button(this);
    tv1.setText("Hello");
    tv1.setLayoutParams(lprams);
    tv1.setId(1);
    rLayout.addView(tv1);

    // second Button
    RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Button tv2 = new Button(this);
    tv1.setText("Hello2");
    newParams.addRule(RelativeLayout.RIGHT_OF, 1);
    tv2.setLayoutParams(newParams);
    tv2.setId(2);
    rLayout.addView(tv2);

这篇关于如何动态地添加视图在XML布局已经宣布RelativeLayout的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 03:29