Search code examples
androidandroid-linearlayoutandroid-buttonhorizontalscrollview

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) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);

    for(int i = 0; i < categories.length; i++) {
        btn = new Button(this);
        btn.setText(categories[i]);
        btn.setBackgroundColor(Color.parseColor("#ffffff"));
        btn.setOnClickListener(buttonClick);
        ll.addView(btn);
        int idx = ll.indexOfChild(btn);
        btn.setTag(Integer.toString(idx));
    }
}

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

        if(v instanceof Button){
            ((Button)v).setTextColor(Color.parseColor("#00aeef"));
         }

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

Solution

  • maybe some iteration through main layout childs?

    for(int i=0; i<ll.getChildCount(); i++){
        if(ll.getChildAt(i) instanceOf Button)
            ((Button)ll.getChildAt(i)).
                setTextColor(Color.parseColor("#00aeef"));
    }
    

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