指定的孩子已经有父母。您必须在孩子的父母上拨打removeview()

发布于 2025-01-25 05:16:40 字数 1105 浏览 3 评论 0原文

我必须经常在两个布局之间切换。错误正在下面发布的布局中发生。

当我的布局第一次称为时,不会出现任何错误,一切都很好。然后,当我调用不同的布局(空白的布局),然后第二次调用我的布局,它会引发以下错误:

> FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

我的布局代码看起来像这样:

    tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code


private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

我知道这个问题以前已经问过,但没有帮助就我而言。

I have to switch between two layouts frequently. The error is happening in the layout posted below.

When my layout is called the first time, there doesn't occur any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it throws the following error:

> FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My layout-code looks like this:

    tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code


private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

I know this question has been asked before, but it didn't help in my case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

情丝乱 2025-02-01 05:16:41

就我而言,我有一个适配器,它可以与回收道一起工作,传递给适配器的项目是具有自己观点的项目。

所需要的只是一个线性延迟以充当每个通过的每个项目的容器,所以我正在做的是在onbindviewholder中在指定位置中获取该项目,然后将其添加到Linearlayout,然后显示。

检查 Docs

当项目从屏幕上滚动时,回收瓶不会破坏其
查看

我的项目,当我向方向滚动时,然后向相反的方向更改 - 快速,显示的物品尚未被破坏,这意味着,这些项目仍然与线性层状容器相关联,然后在我的末端,我'试图固定在另一个容器上,最终是一个孩子已经有了父母。

我的解决方案是检查指定的项目是否具有父,如果有父母,则将其分配给变量,然后调用parentvar.removeview(item),然后分配新父。

这是示例代码(有问题的适配器):

override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {

    holder.linearLayoutContainer.removeAllViewsInLayout()

    val questionWidget: QuestionWidget =
        dataSource[position]

    questionWidget.setValueChangedListener(this)

    holder.linearLayoutContainer.addView(questionWidget)/*addView throws error once in a while*/
    

}


inner class QuestionWidgetViewHolder(mView: View) : 

RecyclerView.ViewHolder(mView) {
        val linearLayoutContainer: LinearLayout =
            mView.findViewById(R.id.custom_question_widget_container)

}

r.id.custom_question_widget_container的内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_question_widget_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical"
    android:padding="10dp" />

因此,QuestionWidget似乎已经保留了父母几乎在外面可见度中近4个步骤,当我滚动到相反的相反时方向快速,我会与父母遇到它,然后我试图将其添加到另一个容器中。

这是修复程序 - 选项1:

        override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
    
            holder.linearLayoutContainer.removeAllViewsInLayout()
    
            val questionWidget: QuestionWidget =
                dataSource[position]
    
            questionWidget.setValueChangedListener(this)
    
       val initialWidgetParent : ViewParent? = questionWidget.parent

//attempt to detach from previous parent if it actually has one
        (initialWidgetParent as? ViewGroup)?.removeView(questionWidget)

        holder.linearLayoutContainer.addView(questionWidget)
            
    
        }

另一个更好的解决方案 - 选项2:

        override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
    
            holder.linearLayoutContainer.removeAllViewsInLayout()
    
            val questionWidget: QuestionWidget =
                dataSource[position]
    
            questionWidget.setValueChangedListener(this)
    
        val initialWidgetParent : ViewParent? = questionWidget.parent
//if it's in a parent container already, just ignore adding it to a view, it's already visible

       if(initialWidgetParent == null) {
           holder.linearLayoutContainer.addView(questionWidget)
       }
            
    
        }

实际上,在将父母添加到父母之前,它是否要问孩子是否有父母。

In my case, I had an adapter which worked with a recyclerView, the items that were being passed to the adapter were items with their own views.

What was required was just a LinearLayout to act as a container for every item passed, so what I was doing was to grab the item in the specified position inside onBindViewHolder then add it to the LinearLayout, which was then displayed.

Checking the basics in docs,

When an item scrolls off the screen, RecyclerView doesn't destroy its
view

Therefore, with my items, when I scroll towards a direction, then change towards the opposite direction - fast, the racently displayed items have not been destroyed, meaning, the items are still associated with the LinearLayout container, then on my end, I'm trying to attach to another container, which ends up with a child having a parent already.

My solution was to check if the specified item has a parent, if it has, I assign it to a variable, then call parentVar.removeView(item), then assign the new parent.

Here's the sample code(Problematic Adapter):

override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {

    holder.linearLayoutContainer.removeAllViewsInLayout()

    val questionWidget: QuestionWidget =
        dataSource[position]

    questionWidget.setValueChangedListener(this)

    holder.linearLayoutContainer.addView(questionWidget)/*addView throws error once in a while*/
    

}


inner class QuestionWidgetViewHolder(mView: View) : 

RecyclerView.ViewHolder(mView) {
        val linearLayoutContainer: LinearLayout =
            mView.findViewById(R.id.custom_question_widget_container)

}

Content of the R.id.custom_question_widget_container:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_question_widget_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical"
    android:padding="10dp" />

So, the questionWidget seems to have been retaining the parent for almost 4 steps outside visibility, and when I scroll to the opposite direction fast, I would encounter it still with its parent, then I'm attempting to add it to another container.

Here's the fix - option 1:

        override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
    
            holder.linearLayoutContainer.removeAllViewsInLayout()
    
            val questionWidget: QuestionWidget =
                dataSource[position]
    
            questionWidget.setValueChangedListener(this)
    
       val initialWidgetParent : ViewParent? = questionWidget.parent

//attempt to detach from previous parent if it actually has one
        (initialWidgetParent as? ViewGroup)?.removeView(questionWidget)

        holder.linearLayoutContainer.addView(questionWidget)
            
    
        }

Another better solution - option 2:

        override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
    
            holder.linearLayoutContainer.removeAllViewsInLayout()
    
            val questionWidget: QuestionWidget =
                dataSource[position]
    
            questionWidget.setValueChangedListener(this)
    
        val initialWidgetParent : ViewParent? = questionWidget.parent
//if it's in a parent container already, just ignore adding it to a view, it's already visible

       if(initialWidgetParent == null) {
           holder.linearLayoutContainer.addView(questionWidget)
       }
            
    
        }

Actually, it's much of asking the child if it has a parent before adding it to a parent.

橘虞初梦 2025-02-01 05:16:41

我尝试了你们建议的所有事情,没有运气。

,我通过将所有绑定的初始化从 ongreate 转移到 increateview 来解决它。

onCreate(){
        binding = ScreenTicketsBinding.inflate(layoutInflater)
}

移至

onCreateView(...){
            binding = ScreenTicketsBinding.inflate(layoutInflater) 
}

I tried all the things that you guys suggested, with no luck.

But, I managed to fix it by moving all my binding initializations from onCreate to onCreateView.

onCreate(){
        binding = ScreenTicketsBinding.inflate(layoutInflater)
}

MOVE TO

onCreateView(...){
            binding = ScreenTicketsBinding.inflate(layoutInflater) 
}
呆橘 2025-02-01 05:16:41

您可以使用此方法检查视图是否有孩子。

public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }

You can use this methode to check if a view has children or not .

public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }
聆听风音 2025-02-01 05:16:41

我的情况不同,孩子的视图已经有一个父母的视图,我将父母视图中的子视图添加到其他父母中。下面的示例代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/lineGap"
>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black1"
    android:layout_gravity="center"
    android:gravity="center"
    />

</LinearLayout>

,我正在夸大此视图并添加到另一条线性层上,然后我从上面的布局中删除了LinaArlayout,并且它

在下面的代码下开始工作,已解决此问题:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:textColor="@color/black1" />

My case was different the child view already had a parent view i am adding the child view inside parent view to different parent. example code below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/lineGap"
>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black1"
    android:layout_gravity="center"
    android:gravity="center"
    />

</LinearLayout>

And i was inflating this view and adding to another LinearLayout, then i removed the LinaarLayout from the above layout and its started working

below code fixed the issue:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:textColor="@color/black1" />
煮酒 2025-02-01 05:16:41

当我使用数据指标进行活动和片段时,这发生在我身上。

对于碎片 - 在onCreateview中,我们可以使用Alfter以传统方式膨胀布局。
在浏览方法中,可以更新绑定对象,因为

 binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding

它解决了我的问题

It happened with me when I was using Databinding for Activity and Fragments.

For fragment - in onCreateView we can inflate the layout in traditional way using inflater.
and in onViewCreated method, binding object can be updated as

 binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding

It solved my issue

有深☉意 2025-02-01 05:16:41

就我而言,我这样做(错误):

...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
  content.setText(quote.content);
...

而不是(良好):

...
for (Quote quote : favQuotes) {
  TextView content = new TextView(context);
  content.setText(quote.content);
...

In my case, I was doing this (wrong):

...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
  content.setText(quote.content);
...

instead of (good):

...
for (Quote quote : favQuotes) {
  TextView content = new TextView(context);
  content.setText(quote.content);
...
向地狱狂奔 2025-02-01 05:16:41

我认为对您问题的正确答案是初始化可运行功能内部的视图:

private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){
        tv = new TextView(getApplicationContext()); 
        et = new EditText(getApplicationContext());

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

因此,它的作用是将视图附加在您的第一次运行中并将其存储在分配的内存中。因此,当您第二次运行时,您将不再具有该视图的可用内存,因此,它需要您先删除视图,然后再尝试再次附加。

因此,如果在您的功能内部,它将始终创建这些视图的实例。

I think the proper answer to your problem is to initialize the Views inside your runnable function:

private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){
        tv = new TextView(getApplicationContext()); 
        et = new EditText(getApplicationContext());

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

So what it does is that it attach the views on your first run and store that on your allocated memory. so when you run it the second time you no longer have the available memory for that view, hence it require you to remove the view first before you try to attach it again.

So if is inside your function it will always create an instance of those views.

零崎曲识 2025-02-01 05:16:41

对我来说,这是非常奇怪的问题,片段XML代码包含具有ID为 root 的视图。我正在用 ViewBinding.Root 返回片段视图。

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val mViewBinding = FragmentMainBinding.inflate(inflater, container, false)
return mViewBinding.root
}

确保XML没有任何视图 id 作为 root

For me, it was very weird problem, the fragment XML code contain a view with id as root. And I was returning fragment view with viewBinding.root.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val mViewBinding = FragmentMainBinding.inflate(inflater, container, false)
return mViewBinding.root
}

Make sure that XML doesn't have any view id as root.

苏辞 2025-02-01 05:16:41

实际上,在这种情况下,当您将一个视图夸大到另一种视图时,然后从另一个视图的父视图中删除所有子视图,请参见下面的设置顺序:

XML:

<LinearLayout
        android:id="@+id/listLlParent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <ListView
            android:id="@+id/imgListview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="2dp"
            android:clipToPadding="false"
            android:paddingBottom="100dp" />
    </LinearLayout>

示例:

    listLlParent.removeAllViews(); // add this line to parent view 
    zoomView.addView(imgListview);
   listLlParent.addView(zoomView);

例外是:

       FATAL EXCEPTION: main
                                                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{-----}: 
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

Actually, In this case, when you have inflated one view to another view, then remove all child views from the another view's parent view, see the setup order below:

Xml :

<LinearLayout
        android:id="@+id/listLlParent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <ListView
            android:id="@+id/imgListview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="2dp"
            android:clipToPadding="false"
            android:paddingBottom="100dp" />
    </LinearLayout>

Example:

    listLlParent.removeAllViews(); // add this line to parent view 
    zoomView.addView(imgListview);
   listLlParent.addView(zoomView);

And the Exception was :

       FATAL EXCEPTION: main
                                                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{-----}: 
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
梦初启 2025-02-01 05:16:41

另一个例外的情况:(不需要删除视图)

在我的情况下,我想在位于水平的croview中的LineareLayout中添加一些TextView。我在循环中以编程方式进行文本视图。我看到,当我添加每个新实例的文本视图时,都可以,但是当我想添加一个旧的textView实例,该实例已经添加到线度laylayout中时,异常出现“ IllegalStateException:指定的孩子已经有父母有父母。

这是我的方法:

public  static TextView createTextView (Context mContext, String text){
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv = new TextView(mContext);
        tv.setLayoutParams(lp);
        tv.setText(text);
        tv.setTextSize(18);
        tv.setPadding(25, 0, 25, 5);
        // tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setGravity(Gravity.CENTER);

        return  tv ;
    }

现在出现例外的方法:

public static void createHorizontalScrollViewWithTextView
            (Context mContext, @NonNull ArrayList<String> list, HorizontalScrollView hSView, LinearLayout linearLayout, EditText etSearch) {
        //It can also create by ImageView
       
        TextView arrowLeft = createTextView(mContext, "  <  ");
        linearLayout.addView(arrowLeft);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println("Catagory in Horizontal : " + s);

            TextView tv = createTextView(mContext, s);
            tv.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    etSearch.setText("  ( "+s+" )" );
                }
            });

            linearLayout.addView(tv);
        }
       
        linearLayout.addView(arrowLeft);  // <= exception Comes to this Line 
        hSView.setVisibility(View.VISIBLE);
    }

修复:

public static void createHorizontalScrollViewWithTextView
            (Context mContext, @NonNull ArrayList<String> list, HorizontalScrollView hSView, LinearLayout linearLayout, EditText etSearch) {
        //It can also create by ImageView

        TextView arrow = createTextView(mContext, "  <  ");
        linearLayout.addView(arrow);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println("Catagory in Horizontal : " + s);

            TextView tv = createTextView(mContext, s);
            tv.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    etSearch.setText("  ( "+s+" )" );
                }
            });

            linearLayout.addView(tv);
        }
        TextView arrowRight = createTextView(mContext, " >  ");  //<= Fix by New View Created, No need To remove Any Views 
        linearLayout.addView(arrowRight);
        hSView.setVisibility(View.VISIBLE);
    }

请参见活动的图片fir行为:(&lt; Bangla English ....):

Another Case of the same Exception: (No Need To Remove Views)

In my case, I want to add some TextView in a LineareLayout which resides in a HorizontalScroView. I made TextView Programmatically in a loop. I see that when I added every new Instance of TextView, it was ok, but when I wanted to add an old instance of TextView which already added to the LinearLayout again, Exception arise "IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."

So, I come to the decision that, though the exception says removeView(), every time it's not necessary to removeView() in all cases.

Here is My Methods :

public  static TextView createTextView (Context mContext, String text){
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv = new TextView(mContext);
        tv.setLayoutParams(lp);
        tv.setText(text);
        tv.setTextSize(18);
        tv.setPadding(25, 0, 25, 5);
        // tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setGravity(Gravity.CENTER);

        return  tv ;
    }

Now the method in which exception arises :

public static void createHorizontalScrollViewWithTextView
            (Context mContext, @NonNull ArrayList<String> list, HorizontalScrollView hSView, LinearLayout linearLayout, EditText etSearch) {
        //It can also create by ImageView
       
        TextView arrowLeft = createTextView(mContext, "  <  ");
        linearLayout.addView(arrowLeft);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println("Catagory in Horizontal : " + s);

            TextView tv = createTextView(mContext, s);
            tv.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    etSearch.setText("  ( "+s+" )" );
                }
            });

            linearLayout.addView(tv);
        }
       
        linearLayout.addView(arrowLeft);  // <= exception Comes to this Line 
        hSView.setVisibility(View.VISIBLE);
    }

Fixing :

public static void createHorizontalScrollViewWithTextView
            (Context mContext, @NonNull ArrayList<String> list, HorizontalScrollView hSView, LinearLayout linearLayout, EditText etSearch) {
        //It can also create by ImageView

        TextView arrow = createTextView(mContext, "  <  ");
        linearLayout.addView(arrow);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println("Catagory in Horizontal : " + s);

            TextView tv = createTextView(mContext, s);
            tv.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    etSearch.setText("  ( "+s+" )" );
                }
            });

            linearLayout.addView(tv);
        }
        TextView arrowRight = createTextView(mContext, " >  ");  //<= Fix by New View Created, No need To remove Any Views 
        linearLayout.addView(arrowRight);
        hSView.setVisibility(View.VISIBLE);
    }

See The below Picture Firs Line of the Activity : ( < bangla English....) :
enter image description here

你是暖光i 2025-02-01 05:16:40

错误消息说您应该做什么。

// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

The error message says what You should do.

// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT
狼性发作 2025-02-01 05:16:40

只需通过论点

stacttoroot = false

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

simply pass the argument

attachtoroot = false

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);
碍人泪离人颜 2025-02-01 05:16:40

我来这里是在搜索我的recyclerview中搜索错误,但解决方案不起作用(显然)。在回收库中,我已经写了原因和解决方案。希望它对某人有帮助。

如果在oncreateviewholder()中遵循以下方法,则会引起错误:

layoutInflater = LayoutInflater.from(context);
return new VH(layoutInflater.inflate(R.layout.single_row, parent));

相反,应该是

return new VH(layoutInflater.inflate(R.layout.single_row, null));

I came here on searching the error with my recyclerview but the solution didn't work (obviously). I have written the cause and the solution for it in case of recyclerview. Hope it helps someone.

The error is caused if in the onCreateViewHolder() the following method is followed:

layoutInflater = LayoutInflater.from(context);
return new VH(layoutInflater.inflate(R.layout.single_row, parent));

Instead it should be

return new VH(layoutInflater.inflate(R.layout.single_row, null));
_失温 2025-02-01 05:16:40

您必须首先从父母那里删除孩子的视图。

如果您的项目位于Kotlin,则您的解决方案看起来与Java略有不同。 Kotlin用为?简化了铸造,如果左侧为空或铸件失败,则返回空。

(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)

Kotlin扩展解决方案

如果需要多次执行此操作,请添加此扩展程序以使您的代码更可读。

childView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parentView = parent as? ViewGroup ?: return
    parentView.removeView(this)
}

如果此视图为null,父视为null或父视图不是ViewGroup,则不会安全执行任何操作

You must first remove the child view from its parent.

If your project is in Kotlin, your solution will look slightly different than Java. Kotlin simplifies casting with as?, returning null if left side is null or cast fails.

(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)

Kotlin Extension Solution

If you need to do this more than once, add this extension to make your code more readable.

childView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parentView = parent as? ViewGroup ?: return
    parentView.removeView(this)
}

It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup

仙女山的月亮 2025-02-01 05:16:40

在Kotlin中简化

 viewToRemove?.apply {
            if (parent != null) {
                (parent as ViewGroup).removeView(this)
            }
        }

Simplified in KOTLIN

 viewToRemove?.apply {
            if (parent != null) {
                (parent as ViewGroup).removeView(this)
            }
        }
撑一把青伞 2025-02-01 05:16:40

framelayout.addview(banneradview); &lt; -----如果您在此行上遇到错误,则如下所示。

if (bannerAdView.getParent() != null)

  ((ViewGroup) bannerAdView.getParent()).removeView(bannerAdView);

   frameLayout.addView(bannerAdView);     <------ now added view

frameLayout.addView(bannerAdView); <----- if you get error on this line the do like below..

if (bannerAdView.getParent() != null)

  ((ViewGroup) bannerAdView.getParent()).removeView(bannerAdView);

   frameLayout.addView(bannerAdView);     <------ now added view
不离久伴 2025-02-01 05:16:40

我的错误是定义这样的观点:

view = inflater.inflate(R.layout.qr_fragment, container);

它丢失了:

view = inflater.inflate(R.layout.qr_fragment, container, false);

My error was define the view like this:

view = inflater.inflate(R.layout.qr_fragment, container);

It was missing:

view = inflater.inflate(R.layout.qr_fragment, container, false);
百变从容 2025-02-01 05:16:40

就我而言,我将ID命名为“ root”,以构成约束布局,这与现有的母体root ID相冲突。

尝试更改ID。

<androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/root"  //<--It should not named as root.
            android:layout_width="match_parent"
            android:layout_height="match_parent"

</androidx.constraintlayout.widget.ConstraintLayout>

In my case, I had id named as "root" for constraint layout, which was conflicting the existing parent root id.

Try to change the id.

<androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/root"  //<--It should not named as root.
            android:layout_width="match_parent"
            android:layout_height="match_parent"

</androidx.constraintlayout.widget.ConstraintLayout>
你与清晨阳光 2025-02-01 05:16:40

如果您使用的是ViewBinding,请确保您指的是正确的绑定!

当我试图从一项活动中夸大自定义对话框时,我遇到了这个问题:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

final AlertBinding alertBinding = AlertBinding.inflate(LayoutInflater.from(this), null, false);

builder.setView(binding.getRoot()); // <--- I was using binding (which is my Activity's binding), instead of alertBinding.

If you're using ViewBinding, make sure you're referring to the right binding!

I had this issue when I was trying to inflate a custom dialog from within an activity:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

final AlertBinding alertBinding = AlertBinding.inflate(LayoutInflater.from(this), null, false);

builder.setView(binding.getRoot()); // <--- I was using binding (which is my Activity's binding), instead of alertBinding.
↘紸啶 2025-02-01 05:16:40

如果其他解决方案不起作用:

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

检查您从片段的OnCreateview返回的内容是单视图还是视图组?就我而言,我将ViewPager放在XML片段的根上,并且正在返回ViewPager,当我在布局中添加了ViewGroup时,我没有更新我现在必须返回ViewGroup,而不是ViewPager(View)。

If other solution is not working like:

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

check for what are you returning from onCreateView of fragment is it single view or viewgroup? in my case I had viewpager on root of xml of fragment and I was returning viewpager, when i added viewgroup in layout i didnt updated that i have to return viewgroup now, not viewpager(view).

囚你心 2025-02-01 05:16:40

在我的情况下,当我想添加父级视图到其他视图时,就会发生

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt);  // ->  crash

这种情况

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);

In my case it happens when i want add view by parent to other view

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt);  // ->  crash

you must add parent view like this

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);
岛歌少女 2025-02-01 05:16:40

我的问题与许多其他答案有关,但是需要进行更改的原因有些不同...我试图将活动转换为片段。因此,我将膨胀代码从OnCreate移到了OnCreateview,但是我忘了从SetContentView转换为Amprate方法,而相同的IllegalStateException将我带到了此页面。

我改变了这一点

binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)

binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)

对此解决了问题。

My problem is related to many of the other answers, but a little bit different reason for needing to make the change... I was trying to convert an Activity to a Fragment. So I moved the inflate code from onCreate to onCreateView, but I forgot to convert from setContentView to the inflate method, and the same IllegalStateException brought me to this page.

I changed this:

binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)

to this:

binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)

That solved the problem.

橘和柠 2025-02-01 05:16:40

就我而言,问题是由于我正在用&lt;布局将父级视图夸大的事实引起的。在这种情况下,addView()引起了崩溃。

View to_add = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, true);
// parent_layout.addView(to_add); // THIS CAUSED THE CRASH

删除 addView() 有助于解决问题。

In my case the problem was caused by the fact that I was inflating parent View with <merge> layout. In this case, addView() caused the crash.

View to_add = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, true);
// parent_layout.addView(to_add); // THIS CAUSED THE CRASH

Removing addView() helped to solve the problem.

冬天旳寂寞 2025-02-01 05:16:40

下面的代码为我解决了:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

注意:错误是来自我的片段类,并且通过覆盖这样的ondestroy方法,我可以解决它。

The code below solved it for me:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.

℉絮湮 2025-02-01 05:16:40

这就是我进行自定义对话框的方式

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
android.view.View views = getLayoutInflater().inflate(layout_file, null, false);

builder.setView(views);
dialog = builder.create();
dialog.show();

我将其更改为它及其对我的作品,希望这会有所帮助

Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(layout_file);
dialog.show();

This is how I do my custom dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
android.view.View views = getLayoutInflater().inflate(layout_file, null, false);

builder.setView(views);
dialog = builder.create();
dialog.show();

I changed it into this and its works for me, I hope this helps

Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(layout_file);
dialog.show();
腻橙味 2025-02-01 05:16:40

检查您是否已经添加了视图

if (textView.getParent() == null)
    layout.addView(textView);

check if you already added the view

if (textView.getParent() == null)
    layout.addView(textView);
往事随风而去 2025-02-01 05:16:40
if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
爱本泡沫多脆弱 2025-02-01 05:16:40

我面临着同样的错误,看看我在做什么。我很糟糕,我试图将相同的视图nativeadView添加到多个framelayouts,通过创建一个单独的视图nativeadView来解决每个。 Framelayout,谢谢

I was facing the same error, and look what I was doing. My bad, I was trying to add the same view NativeAdView to the multiple FrameLayouts, resolved by creating a separate view NativeAdView for each FrameLayout, Thanks

初雪 2025-02-01 05:16:40

就我而言,我意外地从layout.oncreateview()中返回了一个子视图,如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v= inflater.inflate(R.layout.activity_deliveries, container, false);
    RecyclerView rv  = (RecyclerView) v.findViewById(R.id.deliver_list);
    
    return rv; // <- here's the issue
}

解决方案是返回父视图(v)而不是子查看(RV)。

In my case I was accidentally returning a child view from within Layout.onCreateView() as shown below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v= inflater.inflate(R.layout.activity_deliveries, container, false);
    RecyclerView rv  = (RecyclerView) v.findViewById(R.id.deliver_list);
    
    return rv; // <- here's the issue
}

The solution was to return the parent view (v) instead of the child view (rv).

绅刃 2025-02-01 05:16:40

我找到了另一个修复程序:

if (mView.getParent() == null) {
                    myDialog = new Dialog(MainActivity.this);
                    myDialog.setContentView(mView);
                    createAlgorithmDialog();
                } else {
                    createAlgorithmDialog();
                }

在这里,我只有一个if语句检查视图是否有父母,并且如果没有创建新的对话框,设置ContentView并将对话框显示在我的“ createalgorithmdialog()”方法中。

这还可以用OnClickListeners设置正面和负面按钮(确定和取消按钮)。

I found another fix:

if (mView.getParent() == null) {
                    myDialog = new Dialog(MainActivity.this);
                    myDialog.setContentView(mView);
                    createAlgorithmDialog();
                } else {
                    createAlgorithmDialog();
                }

Here i just have an if statement check if the view had a parent and if it didn't Create the new dialog, set the contentView and show the dialog in my "createAlgorithmDialog()" method.

This also sets the positive and negative buttons (ok and cancel buttons) up with onClickListeners.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文