我正在尝试将AddView添加到我的TableLayout上,同时将每行上的项目数量限制为5,因此,如果我有3个项目,则它将创建1行,将加载6个项目,将11个加载3个,等等。使用Android,因此可能是一个简单的修复程序,请告诉我。
`
final TableLayout t1 = (TableLayout) findViewById(R.id.t1); //TableLayout to expand
final TableRow tr1 = new TableRow(this); //Row 1 0-5 items
final TableRow tr2 = new TableRow(this); // Row 2 6-10 itmes
final TableRow tr3 = new TableRow(this);
final TableRow tr4 = new TableRow(this);
final Button finalBtn = btn; //Button that triggers Action
btn.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
// Initialize a new ImageView widget
if (array_Killerimage.size() <= 5)
{
tl.addView(tr1); //Crashes on all these lines
}
if (array_Killerimage.size() <= 10)
{
t1.addView(tr1);
tl.addView(tr2);
}
if (array_Killerimage.size() <= 15)
{
t1.addView(tr1);
t1.addView(tr2);
t1.addView(tr3);
}
if (array_Killerimage.size() <= 20)
{
tl.addView(tr1);
tl.addView(tr2);
tl.addView(tr3);
tl.addView(tr4);
}
错误日志
Process: com.example.appv2, PID: 11200
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:5122)
at android.view.ViewGroup.addView(ViewGroup.java:4953)
at android.widget.TableLayout.addView(TableLayout.java:427)
at android.view.ViewGroup.addView(ViewGroup.java:4893)
at android.widget.TableLayout.addView(TableLayout.java:409)
at android.view.ViewGroup.addView(ViewGroup.java:4866)
at android.widget.TableLayout.addView(TableLayout.java:400)
at com.example.appv2.Main4Activity$1.onClick(Main4Activity.java:) //Line of interest
at android.view.View.performClick(View.java:6892)
at android.widget.TextView.performClick(TextView.java:12693)
at android.view.View$PerformClick.run(View.java:26101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
最佳答案
这意味着您要添加到TabelLayout的视图已经有一个父级。您可以在将视图添加到新Container(TabelLayout)之前简单地从其父视图中删除
在添加视图之前进行此更改。
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
tabelLayout.addView(view);
注意:您只能添加没有父视图的视图,换句话说,您只能添加尚未添加到视图树的视图,添加视图后,您应该从其父视图中删除该视图,然后才能添加到另一个父视图。
编码愉快!!