Search code examples
androidandroid-studioandroid-drawableandroid-buttonandroid-text-color

Android Studio : How to set a Drawable to a buttonTextColor Programatically?


How can I set a drawable for button text color programmatically as in XML ?

I am creating a servel buttons and I want to change their text color when pressed.

The method btn.setTextColor() has an integer as entry which represents a color value so when I put a drawable in there it is considered as color.

private void showDialog(List list) {
    View mView = getLayoutInflater().inflate(R.layout.dialogfor_each_activity, null);
    LinearLayout ll = mView.findViewById(R.id.linearLayout);
    ll.setWeightSum((float)list.size());
    dialog.setContentView(R.layout.dialogfor_each_activity);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = (int) (displaymetrics.widthPixels * 0.90);
    int height = (int) (displaymetrics.heightPixels * 0.50);
    dialog.getWindow().setLayout(width,height);
    dialog.setCancelable(true);
    for (int i = 0; i < list.size(); i++) {
        Button btn = new Button(this);
        btn.setText(list.get(i).toString());
        btn.setTag(list.get(i).toString());
        btn.setId(i);
        btn.setBackgroundResource(R.drawable.strockbtn_white_to_roundbtn_white);
        btn.setTextColor(R.drawable.text_blue_to_white);
        btn.setTextSize(15);
        btn.setTypeface(null, Typeface.BOLD);
        btn.setPadding(0,0,0,0);
        params.setMargins(150, 6, 150, 6);
        btn.setLayoutParams(params);
        btn.setOnClickListener(this);
        ll.addView(btn);
        buttons.add(btn);
    }
    dialog.setContentView(mView);
    dialog.show();
}

I want the buttonTextColor to be set to R.drawable.text_blue_to_white like in XML.

EDIT : This is not a duplicate question I already done what I want in a another way.

I need the equivalent java code for (if it is possible):

android:textColor="@drawable/text_blue_to_white"

Solution

  • You need to have a color resource in res/color/blue_to_white:

    <selector>
        <item 
            android:state_pressed="true"
            android:color="#ffffff"/>
        <item android:color="#0000ff"/>
    </selector>
    

    Then do:

    btn.setTextColor(getResources().getColorStateList(R.color.blue_to_white));
    

    EDIT: Upon revisiting https://developer.android.com/reference/android/content/res/Resources.html#getColorStateList(int), getColorStateList(int) is deprecated in API 23. If your target is >= API 23, simply:

    btn.setTextColor(getResources().getColorStateList(R.color.blue_to_white, getTheme()));