我正在编写一个包含多个片段的 Android 应用程序。在手机上,只会显示一个片段,而在平板电脑上,会显示三个片段。以下是我对不同设备的布局:
平板电脑布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainTopLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:background="@color/activity_background"
android:tag="@string/layout_tablet_landscape" >
<FrameLayout android:id="@+id/leftContainerLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33" />
<FrameLayout android:id="@+id/centerContainerLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33" />
<FrameLayout android:id="@+id/rightContainerLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33" />
</LinearLayout>
手机布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainTopLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/activity_background"
android:tag="@string/layout_phone_portrait" >
<FrameLayout android:id="@+id/mainContainerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_above="@+id/mainBrewAd" />
<com.google.ads.AdView xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/mainBrewAd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adUnitId="##############"
ads:adSize="BANNER"
ads:loadAdOnCreate="true"/>
</RelativeLayout>
这是在主活动的 OnCreate 方法中将片段添加到布局的代码:
if ((layoutTag == LAND_PHONE) || (layoutTag == PORT_PHONE)) {
GravityFragment gravityFragment = (GravityFragment)fragmentManager.findFragmentById(R.id.mainContainerLayout);
if (gravityFragment == null) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.mainContainerLayout, new GravityFragment());
transaction.commit();
}
}
if ((layoutTag == LAND_TABLET) || (layoutTag == PORT_TABLET)) {
GravityFragment gravityFragment = (GravityFragment)fragmentManager.findFragmentById(R.id.leftContainerLayout);
if (gravityFragment == null) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.leftContainerLayout, new GravityFragment());
transaction.commit();
}
}
这是片段的 onStart 方法:
@Override
public void onStart() {
super.onStart();
//Init a brewcalc object
brewCalc = new BrewCalc(getActivity());
//Assign the click listener
Activity topActivity = getActivity();
Button calcButton = (Button)getActivity().findViewById(R.id.gravityCalculateButton);
calcButton.setOnClickListener(calculateListener);
}
当我在手机上启动它时,一切正常。当我在平板电脑上启动它时,我得到一个空指针异常。显然,在这种情况下,findViewById 返回 null。为什么是这样?