Search code examples
androidbuttonhorizontalscrollview

Android change text color of button programmatically


I am creating button dynamically in linearlayout horizontalscrollview and on click i get selected button position.

I want to know how to change text color of selected button?

Here is my code.

String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT", "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));
       // btn.setId(idx);
    }
}

OnClickListener buttonClick = new OnClickListener() {
    public void onClick(View v) {
        String idxStr = Integer.toString(ll.indexOfChild(v));
        //(String)v.getTag();
        Toast.makeText(MainActivity.this, idxStr, 6000).show();
    }
};

Solution

  • check the type and assign the text color

     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("#000000"));
                }
                Toast.makeText(MainActivity.this, idxStr, 6000).show();
            }
        };