2012-01-20 3 views
0

에 의해 레이아웃 객체를 가져올 수 없습니다 이것은 XML 코드 :안드로이드 : 나는 그것의 ID

View mainLayout = findViewById(R.id.mainLayout); 
// Or: LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout); 
Log.d("LAYOUT", mainLayout == null ? "NULL" : "NOT NULL"); // Always prints null 

배치는 항상 null입니다 :

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

자바 코드입니다.

왜 그럴까요? id는 정확하며 다른 모든 요소는 문제없이 가져올 수 있습니다.

+3

보기를 팽창/생성해야합니다. findViewById()에 의해 접근 가능해야한다. 이보기가 표시되는지 (예 : 활동에 표시되는 경우) 또는이 컨텍스트 외부에서 표시해야하는 경우 – NuSkooler

+0

잘 모르겠지만 당신의 프로젝트를 청결하게 만들어야한다고 생각합니다. –

답변

4

다음 코드를 사용하여 이미 활동에 첨부 했습니까?

setContentView(R.layout.layout_id); 
+0

아니, 그것을 해결했습니다. 감사. – Alex

3

보기가 응용 프로그램의 setContentView(ID.OF.LAYOUT)를 통해 현재 표시되는 경우 findViewById() 똑바로에만 작동 호출. 그렇지 않으면 직접 뷰를 팽창해야합니다. 이미 뷰 객체가있는 경우는 다음과 같이 그것에서 다른 뷰를 뽑을 수 :

View v = alreadyInflatedView.findViewById(R.id.idOfChildView);

편집 :

뷰 팽창하는 방법

:

LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.idOfViewToInflate, null); 
+0

감사합니다! 뷰를 가져 오기 전에 setContentView를 호출해야한다는 것을 알지 못했습니다. Android 프로그래밍의 두 번째 날 :) – Alex

1

당신은 설정해야합니다을 귀하의 콘텐츠보기 xml에서

setContentView(R.layout.main); //this will put it on the screen. 
관련 문제