2013-12-14 93 views
-1

我有一个相对布局,我试图添加一个按钮。 我已经看到堆栈溢出的其他例子,但我的似乎并没有工作。 我正在为Android 2.3.3开发。Android 2.33开发 - 以编程方式将按钮添加到相对布局

RelativeLayout referenceView = (RelativeLayout)findViewById(R.layout.referencebook); 

Button btn=new Button(this); 
btn.setId(111); 
btn.setText("test"); 

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 

referenceView.addView(btn, params); 


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:scrollbars="vertical" > 
</RelativeLayout> 
+1

嗨,欢迎来到Stack Overflow。请编辑您的问题以解释什么不适用于您的代码。 “不起作用”可能意味着很多事情。 – 1615903

回答

0

试试这个..

您不能设置findViewByIdlayout

RelativeLayout referenceView = (RelativeLayout)findViewById(R.id.relative_layout_id); 

说明上findViewById(int id)

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/relative_layout_id" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:scrollbars="vertical" > 
</RelativeLayout> 
+0

看看这个链接... 可能对你有帮助。 http://stackoverflow.com/questions/10666019/how-to-add-views-dynamically-to-a-relativelayout-already-declared-in-the-xml-lay –

+0

@DilipMalviya你应该把这个评论在OP – Hariharan

+0

谢谢!然而我的按钮仍然没有被添加到布局。 – user1290717

相关问题