我是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 :(得分:0)
不要在xml中使用“fragment”,而是使用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;
}
}
答案 1 :(得分:0)
替换setDefaultFragement
功能
private void setDefaultFragement() {
ContentFragment fragment = new ContentFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(android.R.id.content,fragment).commit();
}