Programing

Android : 코드에서 속성 값을 얻는 방법은 무엇입니까?

lottogame 2020. 10. 14. 07:21
반응형

Android : 코드에서 속성 값을 얻는 방법은 무엇입니까?


코드에서 textApperanceLarge의 int 값을 검색하고 싶습니다. 아래 코드가 올바른 방향으로 가고 있다고 생각하지만 TypedValue에서 int 값을 추출하는 방법을 알 수 없습니다.

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);

코드 는 Reno가 지적한 대로 textAppearanceLarge 속성이 가리키는 스타일 , 즉 TextAppearance.Large 의 리소스 ID 만 가져옵니다 .

스타일에서 textSize 속성 값 을 가져 오려면 다음 코드를 추가하면됩니다.

int[] textSizeAttr = new int[] { android.R.attr.textSize };
int indexOfAttrTextSize = 0;
TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();

이제 textSizetextApperanceLarge가 가리키는 스타일의 픽셀 단위의 텍스트 크기 이거나 설정되지 않은 경우 -1입니다. 이것은 typedValue.type 이 처음에 TYPE_REFERENCE 유형 이라고 가정 하므로 먼저 확인해야합니다.

16,973,890는 그것의 리소스 ID는 사실에서 온다 TextAppearance.Large


사용

  TypedValue typedValue = new TypedValue(); 
  ((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);

문자열의 경우 :

typedValue.string
typedValue.coerceToString()

기타 데이터 :

typedValue.resourceId
typedValue.data  // (int) based on the type

귀하의 경우 반환되는 것은 TYPE_REFERENCE.

TextAppearance가리켜 야한다는 것을 알고 있습니다.

그것은 :

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?textColorPrimary</item>
</style>

이 문제를 해결하기 위해 Martin이 신용을 얻습니다.

int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = context.obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0, -1);

@ user3121370의 답변에 대한 조사 인 것 같습니다. 그들은 불에 탔습니다. :영형

패딩과 같은 차원 만 필요하면 minHeight (내 경우 : android.R.attr.listPreferredItemPaddingStart). 넌 할 수있어:

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemPaddingStart, typedValue, true);

질문이 그랬던 것처럼, 그리고 나서 :

final DisplayMetrics metrics = new android.util.DisplayMetrics();
WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
int myPaddingStart = typedValue.getDimension( metrics );

제거 된 답변과 같습니다. 이렇게하면 기본 기기 측정 항목을 사용하므로 기기 픽셀 크기 처리를 건너 뛸 수 있습니다. 반환 값은 float이고 int로 캐스트해야합니다.

resourceId와 같이 얻으려는 유형에주의하십시오.


또는 kotlin에서 :

fun Context.dimensionFromAttribute(attribute: Int): Int {
    val attributes = obtainStyledAttributes(intArrayOf(attribute))
    val dimension = attributes.getDimensionPixelSize(0, 0)
    attributes.recycle()
    return dimension
}

이것은 내 코드입니다.

public static int getAttributeSize(int themeId,int attrId, int attrNameId)
{
    TypedValue typedValue = new TypedValue();
    Context ctx = new ContextThemeWrapper(getBaseContext(), themeId);

    ctx.getTheme().resolveAttribute(attrId, typedValue, true);

    int[] attributes = new int[] {attrNameId};
    int index = 0;
    TypedArray array = ctx.obtainStyledAttributes(typedValue.data, attributes);
    int res = array.getDimensionPixelSize(index, 0);
    array.recycle();
    return res;
} 

// getAttributeSize(theme, android.R.attr.textAppearanceLarge, android.R.attr.textSize)   ==>  return android:textSize

참고 URL : https://stackoverflow.com/questions/7896615/android-how-to-get-value-of-an-attribute-in-code

반응형