java - Android中使用FragmentTransaction对象的add方法后应用闪退
问题描述
想在activity中进行fragment的设置和替换。setDefaultFragment()方法中,使用transaction.add(R.id.layFrame, MapsFragment.newInstance('map','map'));语句则应用闪退。注释掉此语句则正常运行。
应用截图xml<?xml version='1.0' encoding='utf-8'?><LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:app='http://schemas.android.com/apk/res-auto' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' tools:context='com.example.tourguide.activity.MainActivity'> <FrameLayout android: android:layout_width='match_parent'android:layout_height='0dp'android:layout_weight='1' /> <com.ashokvarma.bottomnavigation.BottomNavigationBarandroid: android:layout_width='match_parent'android:layout_height='wrap_content'android:layout_gravity='bottom' /></LinearLayout>Activity
public class MainActivity extends AppCompatActivityimplements BottomNavigationBar.OnTabSelectedListener{ private ArrayList<Fragment> fragments; @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//底部导航栏对象BottomNavigationBar bottomNavigationBar= (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);//设置样式、颜色bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);bottomNavigationBar.setActiveColor(R.color.colorPrimary).setInActiveColor('#FFFFFF').setBarBackgroundColor('#ECECEC');//添加导航项bottomNavigationBar.addItem(new BottomNavigationItem(R.drawable.ic_location_on_white_24dp, 'Location')).addItem(new BottomNavigationItem(R.drawable.ic_tracks_on_white_24dp, 'Tracks')).setFirstSelectedPosition(0).initialise();//获取fragment列表,设定默认fragmentfragments = getFragments();setDefaultFragment();//监听bottomNavigationBar.setTabSelectedListener(this); } private ArrayList<Fragment> getFragments() {ArrayList<Fragment> fragments = new ArrayList<>();fragments.add(MapsFragment.newInstance('Map','Map'));fragments.add(TracksFragment.newInstance(3));return fragments; } private void setDefaultFragment(){FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();transaction.add(R.id.layFrame, MapsFragment.newInstance('map','map'));transaction.addToBackStack(null);transaction.commit(); } @Override void init() { } @Override public void onTabSelected(int position) { } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { }}
问题解答
回答1:解决了,原来是fragment中有OnFragmentInteraction接口,而activity中未implement
相关文章:
1. dockerfile - [docker build image失败- npm install]2. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?3. debian - docker依赖的aufs-tools源码哪里可以找到啊?4. docker绑定了nginx端口 外部访问不到5. boot2docker无法启动6. docker start -a dockername 老是卡住,什么情况?7. 如何判断数组写入数据库有重复的值8. macos - mac下docker如何设置代理9. angular.js使用$resource服务把数据存入mongodb的问题。10. docker-compose 为何找不到配置文件?