如何用一个在另一个上面的两个按钮以编程方式创建RelativeLayout?

Kar*_*gan 65 android 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);
Run Code Online (Sandbox Code Playgroud)

Oct*_*ean 139

我编写了一个快速示例来演示如何以编程方式创建布局.

public class CodeLayout extends Activity {

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

        // Creating a new RelativeLayout
        RelativeLayout relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

        // Creating a new TextView
        TextView tv = new TextView(this);
        tv.setText("Test");

        // Defining the layout parameters of the TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);

        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(tv);

        // Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
    }
}
Run Code Online (Sandbox Code Playgroud)

理论上,一切都应该清楚,因为它被评论.如果你不明白的话就告诉我.

  • 虽然此示例有效,但我的实际问题(重叠控件)仍未得到答复.更多搜索在http://stackoverflow.com/questions/2305395/laying-out-views-in-relativelayout-programmatically/2499721#2499721中显示了解决方案.我们应该使用setId()显式设置id.只有这样RIGHT_OF规则才有意义 (5认同)
  • 我不这么认为.只需查看此文档:http://developer.android.com/reference/android/app/Dialog.html#addContentView(android.view.View,android.view.ViewGroup.LayoutParams),其中说"添加其他内容视图到屏幕.在屏幕中的任何现有视图之后添加 - 不删除现有视图" (3认同)

Kar*_*gan 22

如何以编程方式在RelativeLayout中布局视图中找到答案

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

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