由于没有找到 ID 错误的视图,列表片段未出现

List fragment not appearing owing to No view found for ID error

我正在尝试启动一个列表片段,但它似乎只适用于平板电脑。当我 运行 我在手机上的应用程序崩溃时。有谁知道如何解决这个问题?代码如下。

错误

Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 (com.apptacularapps.exitsexpertlondonlite:id/master_container) for fragment FragmentMainList{b76424 #1 id=0x7f0c0050}

MainActivity.java

public class MainActivity extends ActionBarActivity {

    private boolean mTwoPane;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentMainList newFragment = new FragmentMainList();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.master_container, newFragment);
        transaction.commit();

        if (findViewById(R.id.detail_container) != null) {
            mTwoPane = true;
        }
    }
}

activity_main.xml

<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_main"
    android:name="com.apptacularapps.exitsexpertlondonlite.FragmentMainList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentMainList"
    tools:layout="@android:layout/list_content"/>

activity_main.xml (sw600dp)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:showDividers="middle"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/master_container"/>

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:id="@+id/detail_container"/>

</LinearLayout>

FragmentMainList.java

public class FragmentMainList extends android.support.v4.app.Fragment {

    ListView list_main;

    String[] listContent = {
            "Item 1",
            "Item 2",
            "Item 3"
    };

    private boolean mTwoPane;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_main_list, container, false);
        list_main = (ListView)v.findViewById(R.id.list_main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,listContent);
        list_main.setAdapter(adapter);

        return v;
    }
}

因为你有这条线

transaction.replace(R.id.master_container, newFragment);

并且您在 activity_main.xml 中没有任何与 master_container

具有相同 ID 的布局