[英]add linearlayout dynamically into a Relativelayout
我有這個代碼,我想在嵌入在RelativeLayout內的ScrollView內嵌的LinearLayout中動態添加CheckBoxes(RelativeLayout-> ScrollView-> LinearLayout-> My ChechBoxes)
li = (RelativeLayout) findViewById(R.id.mainlayout);
ScrollView sv = new ScrollView(this);
final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
li.addView(sv);
sv.addView(ll);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText("I'm dynamic!");
ll.addView(cb);
}
this.setContentView(sv);
但我得到這個錯誤:
03-12 20:32:14.840: E/AndroidRuntime(945): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
我的RelativeLayout已經在我的XML文件中聲明了我如何解決這個問題?
this.setContentView(sv);
這將嘗試你的滾動型添加到FrameLayout里android.R.id.content
,但你已經取得li
的父母sv
......因此,“指定的小孩已經有母。”
我相信你可以刪除
因為看起來你只想將ScrollView(等)添加到RelativeLayout,而不是替換整個現有布局。 this.setContentView(sv);
查看此http://developer.android.com/training/animation/screen-slide.html下載示例應用程序時,請瀏覽LayoutChangesActivity.java
以下是添加項目的代碼..
private void addItem() {
// Instantiate a new "row" view.
final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
R.layout.list_item_example, mContainerView, false);
// Set the text in the new row to a random country.
((TextView) newView.findViewById(android.R.id.text1)).setText(
COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);
// Set a click listener for the "X" button in the row that will remove the row.
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Remove the row from its parent (the container view).
// Because mContainerView has android:animateLayoutChanges set to true,
// this removal is automatically animated.
mContainerView.removeView(newView);
// If there are no rows remaining, show the empty view.
if (mContainerView.getChildCount() == 0) {
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
mContainerView.addView(newView, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.