2012-09-19 85 views
0

我有一個基於布爾選項創建的視圖,視圖標題爲在單獨的xml文件中定義的socialoptions。當我試圖通過諸如socialoptions.setClickable(true);等方法使用它時,視圖返回null。Android:查看調用時返回null?

Java代碼:

 if (isUserProfile) { 
      Log.d("user","user"); 
      middlelayout = (LinearLayout) findViewById (R.layout.usermiddlelayout); 
     } else { 
      Log.d("item","item"); 
      middlelayout = (LinearLayout) findViewById (R.layout.itemmiddlelayout); 
      socialoptions = (TextView) findViewById (R.id.socialoptions); 
      map = (TextView) findViewById (R.id.map); 
     } 

XML代碼:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/itemmiddlelayout" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:layout_weight="25" 
    android:background="@android:color/transparent" 
    android:clickable="false" 
    android:orientation="horizontal" > 

    <RelativeLayout 
     android:id="@+id/sociallayout" 
     android:layout_width="0dp" 
     android:layout_height="fill_parent" 
     android:layout_weight="2" 
     android:background="@android:color/transparent" 
     android:paddingBottom="0dp" 
     android:paddingRight="10dp" 
     android:paddingTop="10dp" > 

     <TextView 
      android:id="@+id/socialoptions" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:background="@android:color/transparent" 
      android:clickable="false" /> 
    </RelativeLayout> 

    <RelativeLayout 
     android:id="@+id/maplayout" 
     android:layout_width="0dp" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:background="@android:color/transparent" 
     android:paddingBottom="10dp" 
     android:paddingTop="0dp" > 

     <TextView 
      android:id="@+id/map" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:background="@android:color/transparent" 
      android:clickable="false" /> 
    </RelativeLayout> 

</LinearLayout> 
+0

'middlelayout'還有'null'? – Eric

+0

是的,middlelayout也是空的。 – jrquick

+0

那麼我懷疑你沒有從根視圖或者調用'setContentView'的'Activity'引用它。嘗試調用'findViewById(android.R.id.content)'並查看它是否爲'null'。 – Eric

回答

1

按照意見

你不能做你想要做什麼;您無法引用尚未設置的XML佈局。也就是說,您必須首先使用setContentViewinflate such a layout

drawable作爲可引用對象存儲在應用程序中;它作爲APK中的「文件」存在。佈局只是數據,只有在「創建」之後才意味着什麼。

一旦設置了內容視圖或將佈局充氣到視圖中,在引用佈局內容時就不會再收到null對象。

0

如果XML頁面保存爲usermiddlelayout.xml,你可以使用R.layout.usermiddlelayout。如果xml文件中的線性佈局將它的id設置爲android:id =「@ + id/itemmiddlelayout」,則應使用R.id.itemmiddlelayout而不是R.layout.itemmiddlelayout。

這裏,

middlelayout =(的LinearLayout)findViewById(R.id.itemmiddlelayout);

+0

這解決了一個單獨的問題,通過不使middlelayout返回null,但社會選擇仍然。感謝您的幫助。 – jrquick