user3555472 user3555472 - 1 year ago 121
Android Question

Android reset color of dynamic created buttons programmatically

I am creating button dynamically in linearlayout horizontalscrollview and on click I get selected button position. And I changed click button text color. But my problem is that how can I rested other buttons text color.

For example I have 6 or 7 buttons in linearlayout horizontalscrollview, when I clicked on position 1 button so its text color changed, but when I clicked on position 2 button so I want to reset position 1 or all buttons text color. How can I do it?

Here is my code.

String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;

public void onCreate(Bundle savedInstanceState) {

ll = (LinearLayout) findViewById(;

for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
int idx = ll.indexOfChild(btn);

OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));

if(v instanceof Button){

Toast.makeText(MainActivity.this, idxStr, 6000).show();

Answer Source

maybe some iteration through main layout childs?

for(int i=0; i<ll.getChildCount(); i++){
    if(ll.getChildAt(i) instanceOf Button)

you also don't need Button btn; in your Activity, this reference is unused (and keeps only last added Button)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download