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

后端 未结 13 2086
余生分开走
余生分开走 2020-11-29 07:50

I create this post, because i am new at this, and i need a little help. I am doing a little exercise about a application you that put your name, and it returns \"hello (the

相关标签:
13条回答
  • 2020-11-29 08:19

    In onCreate with activity or onCreateView with fragment

     if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
    }
    try {
        view = inflater.inflate(R.layout.fragment_main, container, false);
    } catch (InflateException e) {
    
    }
    
    0 讨论(0)
  • 2020-11-29 08:19

    In my case the problem was I was trying to add same view multiple times to linear layout

    View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
    
     for (int i = 1; i <= totalCount; i++) {
    
         parentLayout.addView(childView);
    
     }
    

    just initialize view every time to fix the issue

     for (int i = 1; i <= totalCount; i++) {
    
         View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
    
          parentLayout.addView(childView);
    
     }
    
    0 讨论(0)
  • 2020-11-29 08:20

    if you are adding the same view repeatedly in a for loop .. if this is the case then try creating the View object of the layout inside the for loop . and add the view in side the for loop

    To avoid such issues

    0 讨论(0)
  • 2020-11-29 08:21

    You just need to initialize your view in onCreate() method and then in onCreateDialog() again before setView() and it should be work!

    0 讨论(0)
  • 2020-11-29 08:21

    frameLayout.addView(yourView); <----- if you are getting error on this line remove view from it's parent first

    if (yourView.getParent() != null)

    ((ViewGroup) yourView.getParent()).removeView(yourView); frameLayout.addView(yourView); (Add view to layout)

    0 讨论(0)
  • 2020-11-29 08:26

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

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_reject, container, false);
    
        Button button = view.findViewById(R.id.some_button);
    
        return button; // <-- Problem is this
    }
    

    The solution was to return the parent view instead of the child view.

    0 讨论(0)
提交回复
热议问题