2016-08-17 73 views
-1

我在android系統是新的。 我想用代碼替換一個片段。這裏是我的代碼。 MainActivity:錯誤充氣類片段,當我更換片段

public class MainActivity extends FragmentActivity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    setDefaultFragement(); 
} 
private void setDefaultFragement() { 
    ContentFragment fragment = new ContentFragment(); 
    FragmentManager manager = getSupportFragmentManager(); 
    manager.beginTransaction().replace(R.id.fra_content,fragment).commit(); 
} 
} 

這裏是我的ContentFragment

public class ContentFragment extends Fragment { 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.fragment_content, container, false); 
} 
} 

mylayout:

<fragment 
    android:id="@+id/fra_content" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_below="@id/fra_title" 
    /> 

但是我得到這些錯誤

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.administrator.myapplication/com.example.administrator.myapplication.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragmet 

回答

0

,而不是使用 「片段」 你xml,使用FrameLayout。如果你想在你的xml中使用一個片段,它必須被指定,因此不需要片段管理器。

所以,在你的XML

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_below="@id/toolbar" 
    android:id="@+id/content"/> 

在你的活動:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
ft.setCustomAnimations(enterAnimation, exitAnimation); 
ft.replace(R.id.content, new ContentFragment()); 
ft.commit(); 

而在你的片段:

public class ContentFragment extends Fragment { 

@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_content, container, false); 
    return rootView; 
} 
} 
+0

非常感謝。我更改了我的代碼,並且工作正常。 –

0

更換setDefaultFragement功能

private void setDefaultFragement() { 
     ContentFragment fragment = new ContentFragment(); 
     FragmentManager manager = getSupportFragmentManager(); 
     manager.beginTransaction().replace(android.R.id.content,fragment).commit(); 
    } 
+0

我看不出有什麼不同。 –

+0

replace(android.R.id.content,fragment) –