style.xml에서 프로그래밍 방식으로 스타일 속성을 검색하는 방법
현재 웹뷰 또는 텍스트뷰를 사용하여 앱 중 하나에서 웹 서비스에서 오는 동적 데이터를 표시하고 있습니다.데이터에 순수 텍스트가 포함된 경우 TextView를 사용하고 styles.xml의 스타일을 적용합니다.데이터에 HTML(대부분 텍스트 및 이미지)이 포함되어 있는 경우 WebView를 사용합니다.
그러나 이 WebView는 스타일이 없습니다.따라서 일반적인 TextView와는 매우 다르게 보입니다.HTML을 데이터에 직접 삽입하기만 하면 웹뷰에서 텍스트 스타일을 지정할 수 있다고 들었습니다.쉽게 들리지만, 이 HTML에서 필요한 값으로 Styles.xml의 데이터를 사용하여 스타일을 변경하면 두 위치에서 색상 등을 변경할 필요가 없습니다.
그럼 제가 이걸 어떻게 할 수 있을까요?광범위한 검색을 수행했지만 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>
저는 주로 텍스트 사이즈와 텍스트 컬러에 관심이 있습니다.
사용자 지정 스타일을 검색할 수 있습니다.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()
shadowColor, shadowDx, shadowDy, shadowRadius와 같은 특정 속성을 사용할 때 @Ole이 제공한 답변이 깨지는 것 같습니다. (이것들은 제가 찾은 몇 개의 속성일 뿐이며, 더 많을 수도 있습니다.
왜 이런 문제가 발생하는지는 알 수 없지만 @AntoineMarks coding style이 문제를 해결해 주는 것 같습니다.
이것이 어떤 특성을 가지고 작동되도록 하는 것은 이런 것일 것입니다.
First, define a stylable to contain the resource ids like so
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);
이 방법을 사용하면 인덱스가 아닌 이름으로 값을 검색할 수 있습니다.
저는 이전의 해결책을 실행할 수 없었습니다.
제 스타일은:
<style name="Widget.TextView.NumPadKey.Klondike" parent="Widget.TextView.NumPadKey">
<item name="android:textSize">12sp</item>
<item name="android:fontFamily">sans-serif</item>
<item name="android:textColor">?attr/wallpaperTextColorSecondary</item>
<item name="android:paddingBottom">0dp</item>
</style>
Android에 대한 StyleAttribute()를 가져옵니다.R.attr.textSize는 "12sp"의 String 결과를 제공하며, 이 결과를 구문 분석해야 합니다.안드로이드용.R.attr.textColor 리소스 파일 XML 이름을 지정했습니다.이것은 너무 번거로웠습니다.
대신 컨텍스트 테마 래퍼를 사용하는 쉬운 방법을 찾았습니다.
TextView sample = new TextView(new ContextThemeWrapper(getContext(), R.style.Widget_TextView_NumPadKey_Klondike), null, 0);
이를 통해 원하는 모든 것을 조회할 수 있는 완전한 스타일의 텍스트 뷰가 제공되었습니다.예를 들어,
float textSize = sample.getTextSize();
Ole과 PrivateMamtora의 답변은 나에게 잘 안 맞았지만, 이것은 잘 맞았습니다.
이 스타일을 프로그래밍 방식으로 읽고 싶었다고 가정해 보겠습니다.
<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
Kotlin을 사용하여 app/library에 Androidx.core:core-ktx 라이브러리를 포함할 경우...
implementation("androidx.core:core-ktx:1.6.0") // Note the -ktx
...TypeArray를 재활용할 필요 없이 다음 중 하나를 사용할 수 있습니다.
// Your desired attribute IDs
val attributes = intArrayOf(R.attr.myAttr1, R.attr.myAttr2, android.R.attr.text)
context.withStyledAttributes(R.style.MyStyle, attributes) {
val intExample = getInt(R.styleable.MyIntAttrName, 0)
val floatExample = getFloat(R.styleable.MyFloatAttrName, 0f)
val enumExample = R.styleable.MyEnumAttrName, MyEnum.ENUM_1 // See Note 1 below
// Similarly, getColor(), getBoolean(), etc.
}
context.withStyledAttributes(R.style.MyStyle, R.styleable.MyStyleable) {
// Like above
}
// attributeSet is provided to you like in the constructor of a custom view
context.withStyledAttributes(attributeSet, R.styleable.MyStyleable) {
// Like above
}
주 1 (이 답변 덕분에)
열거 값을 얻기 위해 다음 확장 함수를 정의할 수 있습니다.
internal inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
getInt(index, -1).let { if (it >= 0) enumValues<T>()[it] else default }
노트2
Androidx.core:core 및 Androidx.core:core:core-ktx와 같은 -ktx 의존성의 차이점은 -ktx 변종이 Kotlin에 유용한 확장 기능을 포함하고 있다는 것입니다.그렇지 않으면, 그들은 똑같습니다.
수락된 솔루션이 작동하지 않는 경우 attr.xml을 attrs.xml로 이름을 변경해 보십시오(저는 효과가 있었습니다).
언급URL : https://stackoverflow.com/questions/13719103/how-to-retrieve-style-attributes-programmatically-from-styles-xml
'sourcecode' 카테고리의 다른 글
mysql 데이터베이스에 중복 입력을 방지하는 가장 좋은 방법 (0) | 2023.09.20 |
---|---|
WordPress, Node, GitLab 및 CLI 사용자 관리 시스템 (0) | 2023.09.20 |
MySQL 데이터베이스에 많은 양의 히트를 기록하는 모범 사례 (0) | 2023.09.20 |
Oracle 오류 ORA-01790을 해결하는 방법은 무엇입니까? (0) | 2023.09.20 |
UITable View 셀에서 UIS 스위치 (0) | 2023.09.20 |