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.