How to programmatically set style attribute in a view

前端 未结 11 2018
北恋
北恋 2020-11-22 06:38

I\'m getting a view from the XML with the code below:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
11条回答
  •  长情又很酷
    2020-11-22 06:55

    For anyone looking for a Material answer see this SO post: Coloring Buttons in Android with Material Design and AppCompat

    I used a combination of this answer to set the default text color of the button to white for my button: https://stackoverflow.com/a/32238489/3075340

    Then this answer https://stackoverflow.com/a/34355919/3075340 to programmatically set the background color. The code for that is:

    ViewCompat.setBackgroundTintList(your_colored_button,
     ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));
    

    your_colored_button can be just a regular Button or a AppCompat button if you wish - I tested the above code with both types of buttons and it works.

    EDIT: I found that pre-lollipop devices do not work with the above code. See this post on how to add support for pre-lollipop devices: https://stackoverflow.com/a/30277424/3075340

    Basically do this:

    Button b = (Button) findViewById(R.id.button);
    ColorStateList c = ContextCompat.getColorStateList(mContext, R.color.your_custom_color;
    Drawable d = b.getBackground();
    if (b instanceof AppCompatButton) {
        // appcompat button replaces tint of its drawable background
        ((AppCompatButton)b).setSupportBackgroundTintList(c);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Lollipop button replaces tint of its drawable background
        // however it is not equal to d.setTintList(c)
        b.setBackgroundTintList(c);
    } else {
        // this should only happen if 
        // * manually creating a Button instead of AppCompatButton
        // * LayoutInflater did not translate a Button to AppCompatButton
        d = DrawableCompat.wrap(d);
        DrawableCompat.setTintList(d, c);
        b.setBackgroundDrawable(d);
    }
    

提交回复
热议问题