[android] styles.xml에서 프로그래밍 방식으로 스타일 속성을 검색하는 방법

현재 WebView 또는 TextView를 사용하여 내 앱 중 하나의 웹 서비스에서 오는 일부 동적 데이터를 표시하고 있습니다. 데이터에 순수 텍스트가 포함 된 경우 TextView를 사용하고 styles.xml의 스타일을 적용합니다. 데이터에 HTML (대부분 텍스트 및 이미지)이 포함 된 경우 WebView를 사용합니다.

그러나이 WebView는 스타일이 지정되지 않습니다. 따라서 일반적인 TextView와 많이 다릅니다. 데이터에 HTML을 직접 삽입하여 WebView의 텍스트 스타일을 지정할 수 있다는 것을 읽었습니다. 이것은 쉽게 들리지만 Styles.xml의 데이터를이 HTML에 필요한 값으로 사용하고 싶습니다. 따라서 스타일을 변경하면 두 위치에서 색상 등을 변경할 필요가 없습니다.

그래서 어떻게 할 수 있을까요? 광범위한 검색을 수행했지만 styles.xml에서 다른 스타일 속성을 실제로 검색 할 방법을 찾지 못했습니다. 여기에 뭔가가 누락되었거나 실제로 이러한 값을 검색 할 수 없습니까?

데이터를 가져 오려는 스타일은 다음과 같습니다.

<style name="font4">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">#E3691B</item>
    <item name="android:paddingLeft">5dp</item>
    <item name="android:paddingRight">10dp</item>
    <item name="android:layout_marginTop">10dp</item>
    <item name="android:textStyle">bold</item>
</style>

나는 주로 textSize와 textColor에 관심이 있습니다.



답변

styles.xml프로그래밍 방식으로 사용자 지정 스타일을 검색 할 수 있습니다 .

에서 임의의 스타일을 정의하십시오 styles.xml.

<style name="MyCustomStyle">
    <item name="android:textColor">#efefef</item>
    <item name="android:background">#ffffff</item>
    <item name="android:text">This is my text</item>
</style>

이제 다음과 같은 스타일을 검색하십시오.

// The attributes you want retrieved
int[] attrs = {android.R.attr.textColor, android.R.attr.background, android.R.attr.text};

// Parse MyCustomStyle, using Context.obtainStyledAttributes()
TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs);

// Fetch the text from your style like this.     
String text = ta.getString(2);

// Fetching the colors defined in your style
int textColor = ta.getColor(0, Color.BLACK);
int backgroundColor = ta.getColor(1, Color.BLACK);

// Do some logging to see if we have retrieved correct values
Log.i("Retrieved text:", text);
Log.i("Retrieved textColor as hex:", Integer.toHexString(textColor));
Log.i("Retrieved background as hex:", Integer.toHexString(backgroundColor));

// OH, and don't forget to recycle the TypedArray
ta.recycle()


답변

@Ole이 제공 한 대답은 shadowColor, shadowDx, shadowDy, shadowRadius와 같은 특정 속성을 사용할 때 깨지는 것 같습니다 (이것들은 내가 찾은 몇 가지 뿐이며 더 많을 수 있습니다)

나는에 관해서는 아무 생각이 이 문제를 내가에 대한 요구하고있는, 발생 여기 지만, @AntoineMarques 코딩 스타일이 문제를 해결하는 것 같다.

어떤 속성으로도이 작업을 수행하려면 다음과 같습니다.


먼저 다음과 같은 리소스 ID를 포함하도록 스타일러를 정의합니다.

attrs.xml

<resources>
    <declare-styleable name="MyStyle" >
        <attr name="android:textColor" />
        <attr name="android:background" />
        <attr name="android:text" />
    </declare-styleable>
</resources>

그런 다음 코드에서이 작업을 수행하여 텍스트를 얻습니다.

TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, R.styleable.MyStyle);
String text = ta.getString(R.styleable.MyStyle_android_text);

이 방법의 장점은 인덱스가 아닌 이름으로 값을 검색한다는 것입니다.


답변

Ole과 PrivatMamtora의 답변은 저에게 잘 맞지 않았습니다.

이 스타일을 프로그래밍 방식으로 읽고 싶다고 가정 해 보겠습니다.

<style name="Footnote">
    <item name="android:fontFamily">@font/some_font</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@color/black</item>
</style>

다음과 같이 할 수 있습니다.

fun getTextColorSizeAndFontFromStyle(
    context: Context,
    textAppearanceResource: Int // Can be any style in styles.xml like R.style.Footnote
) {
    val typedArray = context.obtainStyledAttributes(
        textAppearanceResource,
        R.styleable.TextAppearance // These are added to your project automatically.
    )
    val textColor = typedArray.getColorStateList(
        R.styleable.TextAppearance_android_textColor
    )
    val textSize = typedArray.getDimensionPixelSize(
        R.styleable.TextAppearance_android_textSize
    )

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val typeface = typedArray.getFont(R.styleable.TextAppearance_android_fontFamily)

        // Do something with the typeface...

    } else {
        val fontFamily = typedArray.getString(R.styleable.TextAppearance_fontFamily)
            ?: when (typedArray.getInt(R.styleable.TextAppearance_android_typeface, 0)) {
                1 -> "sans"
                2 -> "serif"
                3 -> "monospace"
                else -> null
            }

        // Do something with the fontFamily...
    }
    typedArray.recycle()
}

Android의 TextAppearanceSpan 클래스에서 영감을 얻었습니다. https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/style/TextAppearanceSpan.java에서 찾을 수 있습니다.


답변

허용되는 솔루션이 작동하지 않으면 attr.xml의 이름을 attrs.xml로 바꾸십시오 (저를 위해 일했습니다)


답변