2012-12-27 136 views
0

爲什麼我總是(FrameLayout)findViewById總是返回null? 該文件存在。 使用Google地圖。 我閱讀了相關的主題。 技術支持: 項目清潔。 刪除文件夾gen。(FrameLayout)findViewById - 返回null?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.travel_map_activity); 
    mapView = (MapView) findViewById(R.id.travelMapView); 

    FrameLayout mainLayout = (FrameLayout) findViewById(R.id.mapFrame);//null 

} 

什麼問題?

<?xml version="1.0" encoding="utf-8"?> 

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/mapFrame" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<TextView 
    android:id="@+id/tvTop" 
    android:layout_width="fill_parent" 
    android:layout_height="20dip" 
    android:background="#FFFFFF" 
    android:gravity="top|center_horizontal" 
    android:text="FLOATING VIEW - TOP" 
    android:textColor="#000000" 
    android:textStyle="bold" /> 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/lvMain" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 
</LinearLayout></FrameLayout> 

travel_map_activity.xml

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

<com.google.android.maps.MapView 
    android:id="@+id/travelMapView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:apiKey="key" /> 

</LinearLayout> 

感謝

+0

那是'travel_map_activity.xml'?我覺得不行,因爲在上面的行上引用了'R.id.travelMapView'。 – Eric

+0

travel_map_activity.xml添加後。 – JDev

回答

0

你正在尋找(travelMapViewmapFrame)在相同的佈局travel_map_activity這兩種意見。由於您提供的佈局根本沒有持有travelMapView,但您沒有在此處獲得NullPointerException

編輯:正如你展示現在,mapFrame不相同的觀點,所以沒有辦法去說......

,有一個,但它贏得了」噸是有用的,因爲setContentView僅示出了一個一次單一佈局。無論如何,你可以仍然可以訪問mapFrame與膨脹的佈局,而不會被實際使用(這是因爲它是完全無用):

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.your_other_layout_with_framelayout, null); 
FrameLayout mainLayout = (FrameLayout) view.findViewById(R.id.mapFrame); 

使用這會讓你從空逃跑,但再次,如果它不在當前視圖中,則不可能使用該FrameLayout。

+0

我沒有顯示只有當NullPointerException FrameLayout時才彈出的所有代碼。 – JDev

+0

檢查Eric的回答和我的編輯。請,請仔細閱讀**兩個答案 – Korcholis

0

你從travel_map_activity.xml膨脹的佈局,其中只包含一個ID:R.id.travelMapView。你不能選擇其他佈局(有一些小的例外更像系統的濫用)項目。

你要麼需要設置的內容視圖取其佈局它是一個包含R.id.mapFrame,或者你需要找到另一種方式來傳遞(可能使用與Intent.putExtra().getIntExtra(),例如包裝的一個Bundle數據;涵蓋這種東西的有other questionsblogs)。

+0

你沒有給出一個很好的答案 – 2012-12-27 01:27:43