Development Tip

내 사용자 정의보기에서 표준 속성 android : text를 사용하는 방법은 무엇입니까?

yourdevel 2020. 12. 7. 21:01
반응형

내 사용자 정의보기에서 표준 속성 android : text를 사용하는 방법은 무엇입니까?


확장 하는 사용자 정의보기작성했습니다 RelativeLayout. 나는 표준을 사용할 수 있도록 내보기, 텍스트가 android:text 없이 를 지정할 필요 <declare-styleable>하고 하지 않고 사용자 정의 네임 스페이스를 사용하여 xmlns:xxx내 사용자 정의보기를 사용할 때마다.

이것은 내 사용자 정의보기를 사용하는 xml입니다.

<my.app.StatusBar
    android:id="@+id/statusBar"
    android:text="this is the title"/>

속성 값은 어떻게 얻을 수 있습니까? android : text 속성을 얻을 수 있다고 생각합니다.

TypedArray a = context.obtainStyledAttributes(attrs,  ???);

그러나이 ???경우에는 무엇입니까 (attr.xml에 스타일링이없는 경우)?


이것을 사용하십시오 :

public YourView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int[] set = {
        android.R.attr.background, // idx 0
        android.R.attr.text        // idx 1
    };
    TypedArray a = context.obtainStyledAttributes(attrs, set);
    Drawable d = a.getDrawable(0);
    CharSequence t = a.getText(1);
    Log.d(TAG, "attrs " + d + " " + t);
    a.recycle();
}

나는 당신이 아이디어를 얻길 바랍니다


편집하다

이를 수행하는 또 다른 방법 (declar-styleable을 지정하지만 사용자 정의 네임 스페이스를 선언 할 필요가 없음)은 다음과 같습니다.

attrs.xml :

<declare-styleable name="MyCustomView">
    <attr name="android:text" />
</declare-styleable>

MyCustomView.java :

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();

이것은 사용자 정의보기에서 표준 속성을 추출하는 일반적인 Android 방법 인 것 같습니다.

Android API 내에서 내부 R.styleable 클래스를 사용하여 표준 속성을 추출하고 R.styleable을 사용하여 표준 속성을 추출하는 다른 대안을 제공하지 않는 것 같습니다.

원본 게시물

표준 구성 요소에서 모든 속성을 가져 오려면 다음을 사용해야합니다.

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView);
CharSequence t = a.getText(R.styleable.TextView_text);
int color = a.getColor(R.styleable.TextView_textColor, context.getResources().getColor(android.R.color.darker_gray)); // or other default color
a.recycle();

다른 표준 구성 요소의 속성을 원한다면 다른 TypedArray를 만드십시오.

표준 구성 요소에 사용할 수있는 TypedArray에 대한 자세한 내용은 http://developer.android.com/reference/android/R.styleable.html참조하세요 .

참고 URL : https://stackoverflow.com/questions/18013971/how-to-use-standard-attribute-androidtext-in-my-custom-view

반응형