Mr_Hmp Mr_Hmp - 4 months ago 13
Android Question

setText() not working on dynamically added buttons in linearLayout

The title says it all.

I am making an application in which i have to add dynamic buttons in a linear layout i have tried:

testButtons = new Button[caseDetails.length()];
for (int i = 0; i < caseDetails.length(); i++) {
temp = caseDetails.getJSONObject(i);
Log.e("TEMP " + i, temp.toString());
testButtons[i] = new Button(this) ;
testButtons[i].setText("Hello Hi");
testButtons[i].setHeight(LayoutParams.WRAP_CONTENT);
testButtons[i].setWidth(LayoutParams.WRAP_CONTENT);
testButtons[i].setPadding(20, 20, 20, 20);
testLayout.addView(testButtons[i]);
}


All i can see on emulator is two buttons with no text. Why is this happening?

Answer

had the same problem.. try this..

testButtons = new Button[caseDetails.length()];

for (int i = 0; i < caseDetails.length(); i++) {
    temp = caseDetails.getJSONObject(i);
    testButtons[i] = new Button(this) ;
    testButtons[i].setText("Hello Hi");
    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    testButtons[i].setPadding(20, 20, 20, 20);
    testLayout.addView(testButtons[i], lp);
}

also make sure your linearLayout's orientation is vertical. Good Luck! :)

Comments