繁体   English   中英

我可以从我的 Java 代码访问和修改 style.xml 吗?

[英]Can I acess and modify styles.xml from my java code?

有没有办法可以从我的 java 代码访问和修改 styles.xml 文件中的样式? 下面代码中的所有 Buttons 都具有相同的样式,如果我可以只编辑该样式的 textSize,那将节省我一些复制和粘贴的时间。

我想也许使用 R.style.styleName 会以某种方式工作,但无法弄清楚。 我在 Google/stackoverflow 上没有发现任何有用的东西。

任何帮助表示赞赏

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);
}

首先在style.xml定义customStyle

 <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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM