2010-07-15 5 views
14

SurfaceView 클래스의 하위 클래스를 만들어 내 자신의보기를 만들었습니다.xml 레이아웃의 사용자 정의보기

그러나 xml 레이아웃 파일에서 추가하는 방법을 알 수 없습니다. 현재 main.xml은 다음과 같습니다 :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

<View 
    class="com.chainparticles.ChainView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    /> 


</LinearLayout> 

내가 무엇을 놓쳤습니까?

편집

더 많은 정보

내보기이

package com.chainparticles; 
public class ChainView extends SurfaceView implements SurfaceHolder.Callback { 
    public ChainView(Context context) { 
     super(context); 
     getHolder().addCallback(this); 
    } 
// Other stuff 
} 

처럼 보인다 그리고 그것은 다음과 같이 작동합니다 :

ChainView cview = new ChainView(this); 
setContentView(cview); 

을하지만에서 사용하려고 할 때 아무 일도 발생하지 않습니다 the XML.

답변

17

당신이 원하는 :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 

    <com.chainparticles.ChainView 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    /> 
</LinearLayout> 

편집 : 팽창하면서 생성자에 getHolder를 호출 할 수 없기 때문에

코드의 나머지 부분을 본 후 아마 던지고. 그래서 View#onFinishInflate

해당 이동 :

@Override 
protected void onFinishInflate() { 
    getHolder().addCallback(this); 
} 

을 그건 당신이 setContentViewActivity의에서 onCreate에서 통화하는 init 함수에서 그 퍼팅 시도 작동하지 않는 경우.

xml에서 생성자를 확장 할 때 View(Context, AttributeSet)View(Context) 대신 호출 되었기 때문에 이전에 작동했을 가능성이 큽니다.

+0

내 첫 번째 레이아웃에서 방금 검은 화면이 나타났습니다. 대신이 앱이 충돌합니다. – monoceres

+0

스택 추적은 무엇입니까? – Qberticus

+0

http://pastebin.com/u2t3jdMt – monoceres

11

예제에서 빠뜨린 것은 태그 이름이었습니다. "보기"가 아닌 "보기"(첫 번째 비 - 자본)로되어 있습니다. 대부분의 경우 클래스 이름을 태그 이름으로 사용할 수 있지만 내부 클래스를 참조하는 Java에서 사용되는 "$"기호는 XML 태그로 제한되어 있기 때문에 클래스가 내부 클래스 인 경우에는 그렇게 할 수 없습니다. 당신이 당신의 XML에 내부 클래스를 사용하려면 그래서, 당신은 다음과 같이 작성해야합니다 :

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 

    <view 
     class="com.chainparticles.Foo$InnerClassChainView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    /> 
</LinearLayout> 

것은 "보기"와 "보기"태그가 모두 스키마에 존재한다는 것입니다. "보기"태그 (대문자로 시작됨)는 View 클래스를 생성하고 "보기"태그는 구문 분석 될 때 클래스 속성을 검사합니다.

+1

OMG 나는 당신을 사랑한다 (엄격히 비 - 플라톤 방식으로)! – samosaris

+0

@SamusArin +1 그 사람을 위해 하하하겠습니다. –

+0

모든 생성자를 추가하십시오. View를 재정의하는 경우 View (Context context), View (Context context, AttributeSet attrs) 및 View (컨텍스트 컨텍스트, AttributeSet attrs, int defStyleAttr) – SoloPilot

관련 문제