gpt4 book ai didi

java - 程序化 View 错误,不确定我做错了什么。必须调用removeView() 子级已经有父级

转载 作者:行者123 更新时间:2023-12-02 04:13:48 26 4
gpt4 key购买 nike

我在尝试以编程方式创建充满按钮的模块化 ScrollView 时遇到此问题。我的 fragment 接受行、列和每个按钮的名称。我想知道为什么使用以下代码会出现此运行时错误。

错误

The specified child already has a parent. You must call removeView() on the child's parent first.

代码

@Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);

//linearLayout from scrollView
LinearLayout linearVertical =
getActivity().findViewById(R.id.linear_layout_vertical);

//LinearLayouts which will each contain buttons
LinearLayout[] linearLayouts = new LinearLayout[mRows];

//
for(int i = 0; i < mRows; i++){
linearLayouts[i] = new LinearLayout(getContext());
linearLayouts[i].setLayoutParams(new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayouts[i].setOrientation(LinearLayout.HORIZONTAL);
}

Button[] buttons = new Button[mRows * mColumns];

//creating buttons / adding button style
for(int i = 0; i < mRows * mColumns; i++){
buttons[i] = new Button(getActivity(), null,R.style.buttonTheme);

if(i < mNames.length){
buttons[i].setText(mNames[i]);
}else{
buttons[i].setText("NULL");
}

buttons[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonPress(v);
}
});
}

for(int i = 0; i < mRows; i++){
for(int j = 0; j < mColumns; j++){
linearLayouts[i].addView(buttons[(i * j) + j]);
}
linearVertical.addView(linearLayouts[i]);
}
}

最佳答案

如下更改最后一个循环,看看它是否有效:

for(int i = 0; i < mRows; i++){
linearVertical.addView(linearLayouts[i]);
for(int j = 0; j < mColumns; j++){
linearLayouts[i].addView(buttons[(i * j) + j]);
}
}

关于java - 程序化 View 错误,不确定我做错了什么。必须调用removeView() 子级已经有父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com