首页 > 解决方案 > Can I acess and modify styles.xml from my java code?

问题描述

Is there a way I can access and modify a style in the styles.xml file from my java code? All of the Buttons in the code below share the same style, and if I could just edit the textSize in that style, that would save me some copying and pasting.

I thought maybe using R.style.styleName would work somehow but couldn't figure it out. I haven't found anything useful on Google/stackoverflow.

Any help is appreciated

public void setNumberButtonsSize(float size){
    ((Button)findViewById(R.id.zero)).setTextSize(size);
    ((Button)findViewById(R.id.one)).setTextSize(size);
    ((Button)findViewById(R.id.two)).setTextSize(size);
    ((Button)findViewById(R.id.three)).setTextSize(size);
    ((Button)findViewById(R.id.four)).setTextSize(size);
    ((Button)findViewById(R.id.five)).setTextSize(size);
    ((Button)findViewById(R.id.six)).setTextSize(size);
    ((Button)findViewById(R.id.seven)).setTextSize(size);
    ((Button)findViewById(R.id.eight)).setTextSize(size);
    ((Button)findViewById(R.id.nine)).setTextSize(size);
}

标签: javaandroidstyles

解决方案


首先customStyle在你的定义style.xml

 <style name="MyCustomStyle">
        <item name="android:textSize">12sp</item>
    </style>

然后 :

// The attributes you want retrieved
        int[] attrs = { android.R.attr.textSize};
// Parse MyCustomStyle, using Context.obtainStyledAttributes()
        TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs);
// Fetching the textSize defined in your style
        int textSize = ta.getInt(0 /* index */, 0 /* defaultVal */);
// OH, and don't forget to recycle the TypedArray
        ta.recycle();

推荐阅读