0

I want to create multiple View layout programmatically and add theme into another layout, in java do that was simple but in kotlin when i try that run time error happens!

my code is:

fun generateAnswersStatus(){

        //@drawable/ui_top_rounded_answer_background_correct

        for(q in match_game!!.getQuestions()!!){


            val v = View(this)

            v.id = q.getId()!!
            v.layoutParams = ViewGroup.LayoutParams(30,40)

            lytAnswerStatuses.addView(v)

            if(q.getUser1Answer() == null){

                v.setBackgroundResource(R.drawable.ui_top_rounded_answer_background_normal)
            }else{

                if(q.getUser1Answer()!!.toInt() == q.getCorrectAnswer()){

                    v.setBackgroundResource(R.drawable.ui_top_rounded_answer_background_correct)
                }else{

                    v.setBackgroundResource(R.drawable.ui_top_rounded_answer_background_wrong)
                }

            }

            lytAnswerStatuses.addView(v)
        }

    }

and error is:

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

why?

2 Answers 2

1

You're adding your View to its parent twice, you have this call duplicated in your code:

lytAnswerStatuses.addView(v)

Simply remove one of the calls to avoid the error.

Sign up to request clarification or add additional context in comments.

Comments

1

You are adding View "v" to the layout before if condition and doing it again after the if condition. So when you are adding it again to the layout after the if condition, your View 'v' already has a parent as it was attached to your layout previously.

So to handle this: You remove one of the 'addView' statements or just remove the parent from view to which it is attached before adding the view second time. with

((ViewGroup)v.getParent().getParent()).removeView((ViewGroup)v.getParent());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.