java - Android中使用FragmentTransaction對象的add方法后應用閃退
問題描述
想在activity中進行fragment的設置和替換。setDefaultFragment()方法中,使用transaction.add(R.id.layFrame, MapsFragment.newInstance('map','map'));語句則應用閃退。注釋掉此語句則正常運行。
應用截圖<?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. python - 關于beautifulsoup獲取文檔內容2. mysql - 僅僅只是把單引號與反斜杠轉義不用prepare statement能否避免sql注入?3. Python爬取網頁requests亂碼4. java - springMVC配置的controller無法返回jsp文件5. javascript - 項目用IE瀏覽器打開修改前端內容,后臺數據修改了,但是前端頁面內容不變,用谷歌瀏覽器測試前端頁面可以刷新,求大神解決。6. MySQL 中怎么修改字段名,不更改屬性?7. java - 白盒加密源碼或者庫8. javascript - 看一些高手寫代碼單獨用 “$”和“_” 來表示變量,什么時候單獨使用這兩個字符?9. 如何通過Java編碼生成Jmeter儀表板報告。(不是Windows或Shell命令)10. 面向對象編程 - java動態加載和類型轉換問題?
