当屏幕方向发生变化时,我目前遇到Fragment
问题。
我已经尝试了类似android:configChanges="orientation"
的内容,但这并没有奏效。
所以问题是:当应用程序在FragmentContainer中加载一个新的Fragment
时,它会崩溃并显示以下日志:
>java.lang.RuntimeException: Unable to start activity ComponentInfo{foo.bar/foo.bar.MainActivity}: android.view.InflateException: Binary XML file line #13:
Binary XML file line #30: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #13: Binary XML file line #30: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #30:
Error inflating class fragment
Caused by: java.lang.IllegalStateException: Fragment foo.bar.BlankFrag did not create a view.
错误的来源是setContentView(R.layout.activity_main)
方法。
相关的activity_main.xml
摘录:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/adView">
<fragment
android:id="@+id/FragFaecher"
class="foo.bar.BlankFrag"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</FrameLayout>
BlankFrag.class
:
public class BlankFrag extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
return rootView;
}
}
fragment_blank.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/ScimaBackground">
</LinearLayout>
相关摘录MainActivity.class
:
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Intent intent = new Intent(getApplicationContext(), SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
boolean firstRun = getSharedPreferences("preferences", MODE_PRIVATE).getBoolean("firstrun", true);
if(firstRun){
getSharedPreferences("preferences", MODE_PRIVATE).edit().putBoolean("firstrun", false).commit();
new dbconnect(this).updateDB();
}
setContentView(R.layout.activity_main);
Fragment fach = new FaecherFrag(); //new Fragment that gets loaded
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.FragFaecher, fach).commit();
答案 0 :(得分:1)
如果要动态加载片段
,则错误地使用<fragment>
标记
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Fragment fach = new FaecherFrag(); //new Fragment that gets loaded
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// This should be the ID of a FrameLayout
ft.replace(R.id.FragFaecher, fach).commit();
所以,像这样改变你的XML
<FrameLayout
android:id="@+id/FragFaecher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/adView">
</FrameLayout>