我遇到了一个与 fragment 相关的问题。我有一个启动画面,它将“加载”3 秒,然后将创建一个新的 Intent
并启动 MainActivity
。
主要 Activity 代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
和相应的 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.paolo.ebolatrack.MainActivity">
<fragment
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.example.paolo.ebolatrack.NewsFragment"
></fragment>
</RelativeLayout>
和 fragment 的 xml:
<FrameLayout 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" tools:context="com.example.paolo.ebolatrack.NewsFragment">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
这是我遇到的错误(完整跟踪 here ):
10-26 12:05:05.153 2855-2855/com.example.paolo.ebolatrack E/AndroidRuntime: FATAL EXCEPTION: main
10-26 12:05:05.153 2855-2855/com.example.paolo.ebolatrack E/AndroidRuntime: Process: com.example.paolo.ebolatrack, PID: 2855
10-26 12:05:05.153 2855-2855/com.example.paolo.ebolatrack E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.paolo.ebolatrack/com.example.paolo.ebolatrack.MainActivity}: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
...
添加 fragment 似乎会使应用程序崩溃。我正在使用 Android Studio。
最佳答案
这里有答案:
Caused by: java.lang.IllegalArgumentException: Binary XML file line #11: Must specify unique android:id, android:tag, or have a parent with an id for com.example.paolo.ebolatrack.NewsFragment
在布局 xml 中为您的 fragment 添加 id:
<fragment
android:id="@+id/some_frag"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.example.paolo.ebolatrack.NewsFragment"
></fragment>
这是缺失的行:
android:id="@+id/some_frag"
关于java - 添加 fragment 会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350742/