(FrameLayout)findViewById - 返回null?

问题描述 投票:0回答:2

为什么我总是(FrameLayout)findViewById总是返回null?该文件存在。使用Google地图。我阅读了相关主题。技术支持:项目清洁。删除文件夹gen。

    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>

谢谢

android android-layout android-framelayout
2个回答
0
投票

你正在从travel_map_activity.xml中扩展布局,它只包含一个ID:R.id.travelMapView。您无法从其他布局中选择项目(有一些小例外,更像是滥用系统)。

您需要将内容视图设置为包含R.id.mapFrame的任何布局,或者您需要找到另一种传递该数据的方法(例如,可能使用BundleIntent.putExtra()打包的.getIntExtra();有other questionsblogs,涵盖这种事情)。


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); 

使用它可以让你从null中逃脱,但是再次,如果它不在你当前的视图中,你就不可能使用那个FrameLayout。

© www.soinside.com 2019 - 2024. All rights reserved.