카테고리 보관물: 안드로이드

안드로이드

Android-사용자 정의 속성이있는 사용자 정의 UI 요소를 만들 수 있다는

사용자 정의 UI 요소를 만들 수 있다는 것을 알고 있습니다 (View 또는 특정 UI 요소 확장을 통해). 그러나 새로 생성 된 UI 요소에 새로운 속성이나 속성을 정의 할 수 있습니까? (상속되지는 않지만 기본 속성 또는 속성으로 처리 할 수없는 일부 특정 동작을 정의하는 새로운 것을 의미합니다)

예 : 내 맞춤 요소 요소 :

<com.tryout.myCustomElement
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Element..."
   android:myCustomValue=<someValue>
/>

따라서 MyCustomValue 를 정의 할 수 있습니까? 있습니까?

고마워



답변

예. 짧은 가이드 :

1. 속성 XML 만들기

/res/values/attrs.xml속성과 유형을 사용하여 내부에 새 XML 파일을 만듭니다.

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="MyCustomElement">
        <attr name="distanceExample" format="dimension"/>
    </declare-styleable>
</resources>

기본적으로 <declare-styleable />모든 사용자 정의 속성 (여기서는 하나만)을 포함하는보기에 대해 하나를 설정해야 합니다. 가능한 유형의 전체 목록을 찾지 못 했으므로 소스를 살펴보아야합니다. 내가 아는 유형은 참조 (다른 리소스에 대한), 색상, 부울, 차원, 부동 소수점, 정수 및 문자열입니다. 입니다. 꽤 자명하다

2. 레이아웃에서 속성 사용

한 가지를 제외하고는 위에서했던 것과 동일한 방식으로 작동합니다. 사용자 정의 속성에는 고유 한 XML 네임 스페이스가 필요합니다.

<com.example.yourpackage.MyCustomElement
   xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Element..."
   customNS:distanceExample="12dp"
   />

꽤 직설적 인.

3. 전달받은 값을 활용하라

사용자 정의보기의 생성자를 수정하여 값을 구문 분석하십시오.

public MyCustomElement(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0);
    try {
        distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f);
    } finally {
        ta.recycle();
    }
    // ...
}

distanceExample 이 예제에서 개인 멤버 변수입니다. TypedArray다른 유형의 값을 구문 분석하기 위해 많은 다른 것이 있습니다.

그리고 그게 다야. 에서 파싱 된 값을 사용하여 View수정하십시오. 예를 들어 onDraw()그에 따라 모양을 변경하려면 에서 사용하십시오 .


답변

res / values ​​폴더에서 attr.xml을 만듭니다. 여기에서 속성을 정의 할 수 있습니다.

<declare-styleable name="">
    <attr name="myCustomValue" format="integer/boolean/whatever" />
</declare-styleable>

그런 다음 레이아웃 파일에서 사용하려면 추가해야합니다.

xmlns:customname="http://schemas.android.com/apk/res/your.package.name"

그런 다음 값을 customname:myCustomValue=""


답변

예, 할 수 있습니다. 그냥 <resource>태그를 사용하십시오 .
이렇게 :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

공식 웹 사이트에서 링크


답변