티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to retrieve style attributes programmatically from styles.xml
styles.xml에서 프로그래밍 방식으로 스타일 속성을 검색하는 방법은 무엇인가요?
문제 내용
Currently I'm using either a WebView or a TextView to show some dynamic data coming from a webservice in one of my apps. If the data contains pure text, it uses the TextView and applies a style from styles.xml. If the data contains HTML (mostly text and images) it uses the WebView.
현재 앱 중 하나에서 웹 서비스에서 동적 데이터를 보여주기 위해 WebView 또는 TextView를 사용하고 있습니다. 만약 데이터가 순수한 텍스트라면, TextView를 사용하고 styles.xml에서 스타일을 적용합니다. 만약 데이터가 HTML(대부분 텍스트와 이미지)를 포함한다면, WebView를 사용합니다.
However, this WebView is unstyled. Therefor it looks a lot different from the usual TextView. I've read that it's possible to style the text in a WebView simply by inserting some HTML directly into the data. This sounds easy enough, but I would like to use the data from my Styles.xml as the values required in this HTML so I won't need to change the colors et cetera on two locations if I change my styles.
하지만, 이 WebView는 스타일이 없습니다. 그래서 일반적인 TextView와 매우 다르게 보입니다. 웹뷰에서 텍스트를 스타일링하는 것이 가능하다고 읽었습니다. 데이터에 HTML을 직접 삽입함으로써 이를 수행할 수 있습니다. 이것은 충분히 쉬워 보이지만, 내 스타일을 변경하면 두 곳에서 색상 등을 변경할 필요가 없도록 HTML에 필요한 값으로 내 styles.xml의 데이터를 사용하고 싶습니다.
So, how would I be able to do this? I've done some extensive searching but I have found no way of actually retrieving the different style attributes from your styles.xml. Am I missing something here or is it really not possible to retrieve these values?
그렇다면, 이것을 어떻게 할 수 있을까요? 광범위한 검색을 해 보았지만, 실제로 styles.xml에서 다른 스타일 속성을 검색할 수 있는 방법을 찾을 수 없었습니다. 여기서 뭔가 빠뜨린 것이 있는 건가요, 아니면 이러한 값들을 검색하는 것이 불가능한 건가요?
The style I'm trying to get the data from is the following:
저는 다음과 같은 스타일에서 데이터를 가져오려고 합니다.
<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>
I'm mainly interested in the textSize and textColor.
저는 주로 textSize와 textColor에 관심이 있습니다.
높은 점수를 받은 Solution
It is possible to retrieve custom styles from styles.xml
programmatically.
styles.xml에서 사용자 정의 스타일을 프로그래밍 방식으로 검색하는 것이 가능합니다.
Define some arbitrary style in 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>
Now, retrieve the styles like this
이제 이렇게 스타일을 검색하세요.
// 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()
가장 최근 달린 Solution
I was not able to get the earlier solutions to work.
이전 솔루션을 작동시키지 못했습니다.
My style is:
제 스타일은 다음과 같습니다.
<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>
The obtainStyledAttributes() for android.R.attr.textSize gives String results of "12sp" which I then have to parse. For android.R.attr.textColor it gave a resource file XML name. This was much too cumbersome.
android.R.attr.textSize에 대한 obtainStyledAttributes()는 "12sp"와 같은 문자열 결과를 반환하므로 이를 파싱해야 합니다. android.R.attr.textColor에 대해서는 XML 리소스 파일 이름이 반환되었습니다. 이 방법은 너무 불편합니다.
Instead, I found an easy way using ContextThemeWrapper.
대신, ContextThemeWrapper를 사용한 쉬운 방법을 찾았습니다.
TextView sample = new TextView(new ContextThemeWrapper(getContext(), R.style.Widget_TextView_NumPadKey_Klondike), null, 0);
This gave me a fully-styled TextView to query for anything I want. For example:
이 방법은 내가 원하는 모든 것을 쿼리할 수 있는 완전히 스타일이 지정된 TextView를 제공했다. 예를 들면:
float textSize = sample.getTextSize();
출처 : https://stackoverflow.com/questions/13719103/how-to-retrieve-style-attributes-programmatically-from-styles-xml
'개발 > 안드로이드' 카테고리의 다른 글
"Looper.prepare()를 호출하지 않은 스레드 내에서 핸들러를 생성할 수 없습니다."오류 수정하기 (0) | 2023.03.05 |
---|---|
안드로이드에서 스크롤 뷰 안에 리스트 뷰 사용하기 (0) | 2023.03.05 |
안드로이드에서 앱의 공유 프리퍼런스 데이터 삭제하기 (0) | 2023.03.04 |
다른 앱과 콘텐츠를 공유하기 위해 지원되는 FileProvider 사용하기 (0) | 2023.03.02 |
TextView의 텍스트 스타일을 프로그래밍 방식으로 설정하기 (0) | 2023.03.02 |