gpt4 book ai didi

java - Android Studio AddView TableLayout,必须removeChild错误?

转载 作者:行者123 更新时间:2023-12-02 10:07:08 25 4
gpt4 key购买 nike

我试图将 AddView 添加到我的 TableLayout 中,同时将每行上的项目数量限制为 5,所以如果我有 3 个项目,它将生成 1 行,6 个项目将加载 2 个项目,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 的 View 已经有一个父 View 。您可以简单地从其父 View 中删除 View ,然后再添加到新的容器(TabelLayout)

在添加 View 之前进行此更改。

if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
tabelLayout.addView(view);

注意:您只能添加没有父级的 View ,或者换句话说,您只能添加尚未添加到 View 树中的 View ,一旦添加,您应该从其父级中删除该 View ,然后才能添加到另一位家长。

编码愉快!!

关于java - Android Studio AddView TableLayout,必须removeChild错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55274708/

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