2012-12-27 137 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