Могу ли я получить доступ и изменить файл styles.xml из своего кода Java? - PullRequest
0 голосов
/ 18 мая 2019

Есть ли способ получить доступ и изменить стиль в файле styles.xml из моего кода Java?Все кнопки в приведенном ниже коде имеют одинаковый стиль, и если бы я мог просто отредактировать 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);
}

1 Ответ

0 голосов
/ 18 мая 2019

сначала определите 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();
...