0

I have a number of linear layouts that are empty, i want to add to add an image to any one random layout programaticaly, to test this, i add one image programaticaly to one layout after app launch and it works really fine, however am not able to obtain a similar behavior when i manipulate data and call set-view in the onclicklistener of a button.

First of all i have this method which generates a random number in a list i provide

private int getRandomNumberfromlist() {
    ArrayList<Integer> lista = new ArrayList<Integer>();
    lista.add(13);
    lista.add(17);
    lista.add(2);
    lista.add(10);
    lista.add(14);
    lista.add(18);
    lista.add(3);
    lista.add(11);
    lista.add(15);
    lista.add(19);
    lista.add(4);
    lista.add(8);
    Collections.shuffle(lista);
    int chosen = lista.get(0);
    return chosen;
}

When it returns chosen i save it in a variable as such:

 //Obtain
   int machine_has_generated_number = getRandomNumberfromlist();

I have set one, two, three as ids of my different linearlayouts, so i check to see if the number matches either of these and as a result add the image to that layout which matches as follows.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    // Add image.
    final Button imageview = new Button(this);
    imageview.setBackgroundColor(Color.RED);
    imageview.setLayoutParams(params);

    nineteen = findViewById(R.id.nineteen);
    four = findViewById(R.id.four);
    eight = findViewById(R.id.eight);

    if (machine_has_generated_number == 8) {
        eight.addView(imageview);
    } else if (machine_has_generated_number == 19) {
        nineteen.addView(imageview);
    } else if (machine_has_generated_number == 4) {
        four.addView(imageview);
    } 

This works perfectly inside the main function, but if i attempt to do the above and set view after the onclick of a button it fails and gives me the error. "Child already has a parent, i should call removeView on its parent". The result i get without removing the view is what i need inside the onclicklistener.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
John Kaita
  • 15
  • 9
  • Have you tried this approach? You need tom call the parent view of you view.https://stackoverflow.com/questions/28071349/the-specified-child-already-has-a-parent-you-must-call-removeview-on-the-chil – Maxim M Mar 09 '20 at 11:40
  • Thanks @GuessWho for the pointer,i had attempted that answer previously but had interchanged the position for for parent and the imageview while setting the view, so it was removing the layout instead, but upon checking again and correcting it has worked. – John Kaita Mar 09 '20 at 11:58
  • Happy to hear :) – Maxim M Mar 09 '20 at 14:10

0 Answers0