2010-12-14 4 views
7

Android에서 맞춤 View을 만들고 싶습니다. 나는 가능한 한 간단하게하려고 노력했으며 거의 ​​빈 클래스 인 MyView을 만들고 그것을 내 LinearLayout에 사용했지만 "강제 닫기"로 시작하면 응용 프로그램이 실패합니다. 간단한 사용자 정의 View을 어떻게 할 수 있습니까? Building Custom Components에 따르면 ViewonMeasure()을 덮어 쓰지 않으면 100x100 크기가됩니다.간단한 사용자 정의보기를 만드는 방법은 무엇입니까?

public class MyView extends View { 

    public MyView(Context context) { 
     super(context); 
    } 
} 

그리고 함께 LinearLayout에 사용 : 내가 잘못

<view 
    class="com.example.MyView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.0" /> 

을 뭐하는 거지?


내가 제안 itemon 생성자 및 슈퍼 클래스에 대응하는 전화를 사용하는 경우. 그런 다음 "강제 종료"가 사라졌지 만 LinearLayout이 손상되어 MyView 이후의 구성 요소가 표시되지 않습니다. 여기

main.xml입니다 :

public MyView(Context context, AttributeSet attrs) 

는 안드로이드 프레임 워크는 위의 생성자에서 볼 수있는 UI를 구축하려고합니다 :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    > 
<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.0" 
    android:background="#f00" 
    android:text="Hello" 
/> 
<view 
    class="com.example.MyView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.0" 
/> 
<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.0" 
    android:background="#00f" 
    android:text="World" 
/> 
</LinearLayout> 
+0

여기에서 좋은 샘플을 참고하십시오. [http://www.sgoliver.net/blog/?p=1457](http://www.sgoliver.net/blog/?p=1457) –

+0

나는 비슷합니다. 필요합니다. 당신이 필요로하는 것을 갖췄습니까? . 일부 코드 plz를 공유하십시오 – Nepster

답변

9

은이 같은 다른 생성자 메서드를 정의 할 수있을 수 있습니다 .

+0

고마워요, 그건 "강제 종료"메시지를 제거하지만, 내 'LinearLayout'은 고장 났고, 이후의 구성 요소는 보이지 않습니다. – Jonas

+2

나는 onMeasure()도 오버라이드해야했다. 이제는 훌륭하게 작동합니다. – Jonas

9

Android 개발자 가이드에는 맞춤 구성 요소 작성 섹션이 있습니다. 불행하게도, XML 속성에 대한 설명은 레이아웃 파일 내부의 컨트롤을 선언하고 클래스 초기화 내에서 실제로 값을 처리하지는 않습니다. 단계는 다음과 같습니다

선언 값 속성 \ attrs.xml이

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="MyCustomView"> 
     <attr name="android:text"/> 
     <attr name="android:textColor"/>    
     <attr name="extraInformation" format="string" /> 
    </declare-styleable> 
</resources> 

을 주목 선언-styleable 태그에 규정되지 않은 이름의 사용. extraInformation과 같은 표준이 아닌 안드로이드 속성은 선언 된 타입을 가질 필요가 있습니다. 수퍼 클래스에서 선언 된 태그는 다시 선언 할 필요없이 하위 클래스에서 사용할 수 있습니다.

가 초기화에 대한 속성 세트를 사용하는 두 개의 생성자가 있기 때문에 생성자

만들기, 생성자를 호출 할 수있는 별도의 초기화 방법을 만드는 것이 편리하다.

private void init(AttributeSet attrs){ 
    TypedArray a=getContext().obtainStyledAttributes(attrs,R.styleable.MyCustomView); 
    //Use a 
    Log.i("test",a.getString(R.styleable.MyCustomView_android_text)); 
    Log.i("test",""+a.getColor(R.styleable.MyCustomView_android_textColor, Color.BLACK)); 
    Log.i("test",a.getString(R.styleable.MyCustomView_android_extraInformation)); 
    //Don't forget this 
    a.recycle(); 
} 

R.styleable.MyCustomView 각 요소는 속성의 ID 인 자동 생성 INT [] 자원이다. 속성 이름을 요소 이름에 추가하여 XML의 각 특성에 대한 속성을 생성합니다. 그런 다음 다양한 get 함수를 사용하여 TypedArray에서 속성을 검색 할 수 있습니다. 속성이 XML에 정의되어 있지 않은 경우, null이 리턴됩니다. 물론 반환 형식이 기본 형식 인 경우를 제외하고는 두 번째 인수가 반환됩니다.

모든 속성을 검색하지 않으려면이 배열을 수동으로 생성 할 수 있습니다. 표준 Android 속성의 ID는 android.R.attr에 포함되며이 프로젝트의 속성은 R입니다. attr.

int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor}; 

향후 변경 될 수있는이 스레드에 따라 android.R.styleable에는 아무 것도 사용하지 마십시오. 한 곳에서 모든 상수를 보는 것이 유용하기 때문에 여전히 문서에 있습니다.

에 xmlns 네임 스페이스 선언을 포함 같은 레이아웃 \의 main.xml에 같은 레이아웃 파일을 사용하여 응용 프로그램 = "http://schemas.android.com/apk/res/com.mycompany .projectname "

최상위 XML 요소에 있습니다.

<com.mycompany.projectname.MyCustomView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@android:color/transparent" 
    android:text="Test text" 
    android:textColor="#FFFFFF" 
app:extraInformation="My extra information"; 
/> 

정규화 된 이름을 사용하여 사용자 지정보기를 참조하십시오.

안드로이드 LabelView와 샘플

당신이 완전한 예를 원하는 경우, 안드로이드 라벨보기 샘플 봐.

LabelView.java

TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView); 
CharSequences=a.getString(R.styleable.LabelView_text); 
attrs.xml 

<declare-styleable name="LabelView"> 
    <attr name="text"format="string"/> 
    <attr name="textColor"format="color"/> 
    <attr name="textSize"format="dimension"/> 
</declare-styleable> 

custom_view_1.xml

<com.example.android.apis.view.LabelView 
    android:background="@drawable/blue" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    app:text="Blue"app:textSize="20dp"/> 

이 네임 스페이스 속성과 함께있는 LinearLayout에 포함되어 있습니다 :

의 xmlns : 응용 프로그램 = "HTTP : // schemas.android.com/apk/res/com.example.android.apis "

관련 문제