bit of a rough time getting this to work and its an understanding piece on my end…
If i have a spinner item that contains the text “The [item] is [color]” and upon selecting this, I would like it to populate a… tablerow or something like that(or just a relativelayout)… with buttons and there would be two buttons, [item] and [color], stacked one on the other.
public void onItemSelected(AdapterView<?> parentview, View arg1, int position, long id)
{
final TableLayout t1 = (TableLayout)findViewById(R.id.button_items);
final TableRow tr = new TableRow(t1.getContext());
ArrayList<String> words = Create_ArrayList(R.raw.titles);
// Create_ArrayList just parses known words like the [item] and [color] items and puts them into an array… for enumeration purposes later on.
String sentence = (String) spin.getSelectedItem();
if(sentence.contains("[item]"))
{
String line = words.get(1);
ArrayList<String> x = getParts(line);
//arraylist should just be [item] and [color] at this point…
Toast.makeText(getBaseContext(), Integer.toString(x.size()), Toast.LENGTH_SHORT).show();
for(int i = 0; i<x.size(); i++)
{
Toast.makeText(getBaseContext(), x.get(i), Toast.LENGTH_LONG).show();
Button btn = new Button(tr.getContext());
btn.setText(x.get(i));
btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(btn);
t1.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
}
}
but i keep getting…
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
and the buttons dont show up… app just crashes… into a mountain.
help is much appreciated… Thanks all!
In the first code block
you already have the view of t1, but again in the third code block you are adding the view
that is the reason for your exception.
When a View is allready used (e.g., you got it with findViewById, don’t use addView on it). When you want to add a view, use addView with a NEW view. You can add several of these new views to one view, but you cannot add that one view multiple times.
This is what i found in some other post