【发布时间】:2017-06-11 11:08:33
【问题描述】:
这是主要活动 XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#71b7d6"
tools:context="com.csdelta.haroon.fragmentpractice.MainActivity">
<!--Binary XML file line #13 -->
<fragment
android:id="@+id/my_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.csdelta.haroon.fragmentpractice.MyFragment"/>
</LinearLayout>
这是片段活动 XML
<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:background="#f7dc0f"
tools:context="com.csdelta.haroon.fragmentpractice.MyFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello, This is Fragment"
android:textSize="25dp"
android:layout_margin="20dp"
android:textColor="#000"
/>
</LinearLayout>
这是主要活动 Java 文件
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Haroon", "onCreate");
setContentView(R.layout.activity_main);
}
}
这里是片段 Java 文件
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d("Haroon", "onCreateView");
return inflater.inflate(R.layout.fragment_fragment_layout, container, false);
}
}
我收到的 logcat 消息说:
java.lang.RuntimeException:无法启动活动 组件信息{com.csdelta.haroon.fragmentpractice/com.csdelta.haroon.fragmentpractice.MainActivity}: android.view.InflateException:二进制 XML 文件第 13 行:二进制 XML 文件第 13 行:膨胀类片段时出错 引起:android.view.InflateException:二进制 XML 文件第 13 行:二进制 XML 文件第 13 行:膨胀类错误 分段 原因:android.view.InflateException: Binary XML file line #13: Error inflating class fragment 引起:android.app.Fragment$InstantiationException:试图实例化一个 com.csdelta.haroon.fragmentpractice.MyFragment 类
那不是片段
这是完整的 LogCat: https://pastebin.com/iss7ui16
【问题讨论】:
-
在您的情况下,您应该使用
FragmentActivity而不是Activity -
非常感谢。它通过扩展到 FragmentActivity 而不是 Activity 来工作。
标签: java android xml android-fragments