根据对existing question的回答,以前在android的片段中使用片段会出现问题,但是现在应该有一种让Android能够处理它们的方法。
虽然现有问题涉及用Java创建片段,但我想通过以下方式直接在Xml中创建片段:
<fragment
android:layout_width="100dp"
android:layout_height="100dp"
class="com.ra.ra_e_akte.fragments.MyFragment"
android:id="@+id/myFragment"
/>
不幸的是,我得到了错误:
2019-07-29 15:37:06.586 16529-16529/com.ra.ra_e_akte E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ra.ra_e_akte, PID: 16529
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ra.ra_e_akte/com.ra.ra_e_akte.activities.DefaultStacksActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #66: Binary XML file line #66: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2962)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3037)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1701)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6949)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #66: Binary XML file line #66: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #66: Binary XML file line #66: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #66: Error inflating class fragment
Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.ra.ra_e_akte.fragments.SyncButton: calling Fragment constructor caused an exception
at androidx.fragment.app.Fragment.instantiate(Fragment.java:532)
onCreate在父片段中:
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.header_fragment, container, false)
return view
}
是否存在一种在其他片段的xml内声明片段的有效方法?
答案 0 :(得分:2)
<fragment android:name="com.ra.ra_e_akte.fragments.MyFragment"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/myFragment"
/>
尝试此代码