2013-12-14 92 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

相關問題