這是主要活動XML我的Android應用程序崩潰下來的時候我加片段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: Unable to start activity ComponentInfo{com.csdelta.haroon.fragmentpractice/com.csdelta.haroon.fragmentpractice.MainActivity}: android.view.InflateException: Binary XML file line #13: Binary XML file line #13: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #13: Binary XML file line #13: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.csdelta.haroon.fragmentpractice.MyFragment
不是片段
下面是完整的logcat: https://pastebin.com/iss7ui16
在你的情況下,你應該使用'FragmentActivity'而不是'Activity' – x0r
[Android SDK錯誤:嘗試實例化一個不是片段的類](https://stackoverflow.com/questions/24213756/android -sdk-error-trying-instantiate-a-class-that-not-a-fragment) – x0r
非常感謝。它通過擴展到FragmentActivity而不是Activity來工作。 –