Boo Boo - 22 days ago 7
Android Question

Dynamically adding buttons into a table or grid like form layout programmatically

I have been on this problem for a while now.
I am hoping to gather top trending keywords and place into an ArrayList.
Each keyword is to be placed on a toggleButton, (user selects keyword and it enhances search). I need the buttons to be in a grid like form on the Android mobile app, I also need the buttons to be placed in an ArrayList so I can reference later. I've tried so many different loops, for loops and loops in loop and keep hitting the same two problems:

prob 1) either the keywords are not read, or repeated in each column if I create the buttons within the layout loop.

prob 2) I create the buttons first and then reference to them in the layout loop and I get a error message:


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


I've scanned the internet, I've tried different methods and I think its just something I am missing in my code (this layer of code is one of many layers, this one holds the buttons...any pointers will be appreciated.

trending = new ArrayList<String>() {
{
add("one"); add("two"); add("three") ;add("four");add("five");
add("six");add("seven");add("eight");add("nine");add("ten");
add("eleven");
}};

//LAYOUT SETTINGS 5
TableLayout rLayout5 = new TableLayout(this);
rLayout5.setOrientation(TableLayout.VERTICAL);
LayoutParams param7 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
param7.addRule(RelativeLayout.BELOW, rLayout4.getId());
rLayout5.setBackgroundColor(Color.parseColor("#EEEBAA"));

rLayout5.setLayoutParams(param7);
// List<ToggleButton> togButtStore = new ArrayList<ToggleButton>();

int i = 0 ;
while (i < trending.size()){
if (i % 3 == 0){
tr = new TableRow(this);
rLayout5.addView(tr);
}
toggBtn = new ToggleButton(this);
toggBtn.setText(trending.get(i));
toggBtn.setId(i);
toggBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//something here
}
});
tr.addView(toggBtn);
i++;
}
rLayout5.addView(tr); ///<---error points to this line
root.addView(rLayout1);
rLayout1.addView(text1);
root.addView(rLayout4);
root.addView(rLayout3);
root.addView(rLayout5);
setContentView(root);
}

Answer

You are adding tr twice to the rLayout5. Delete the line where your error is....

Comments