java - 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);
}
解决方案
首先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();
推荐阅读
- c# - 如何获取列表
在转换器类 wpf - c# - 如何在引用表中插入外键?
- node.js - 无法将猫鼬连接到 Atlas-MogoDB
- python - 如何强制外部python包使用代理请求
- windows-installer - 如何进行 Foundation 框架安装
- linux - 如何创建一个 url 以访问在 linux 服务器上运行的 docker 服务
- python - 将带有 excel 表的 pandas 转换为 excel 文件
- sql-server - TSQL 表设计:如何在数据库表中表示“null 的原因”类别?
- javascript - 如何将多张图片上传到 Firebase 并下载 URL
- javascript - Apple 用户无法使用服务 ID 登录,但在 iOS 应用上没有问题