想在activity中进行fragment的设置和替换。setDefaultFragment()方法中,使用transaction.add(R.id.layFrame, MapsFragment.newInstance("map","map"));
语句则应用闪退。注释掉此语句则正常运行。

public class MainActivity extends AppCompatActivity
implements BottomNavigationBar.OnTabSelectedListener{
private ArrayList 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列表,设定默认fragment
fragments = getFragments();
setDefaultFragment();
//监听
bottomNavigationBar.setTabSelectedListener(this);
}
private ArrayList getFragments() {
ArrayList 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) {
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
解决了,原来是fragment中有OnFragmentInteraction接口,而activity中未implement