android add fragment,Android中使用FragmentTransaction对象的add方法后应用闪退
想在activity中進行fragment的設置和替換。setDefaultFragment()方法中,使用transaction.add(R.id.layFrame, MapsFragment.newInstance("map","map"));
語句則應用閃退。注釋掉此語句則正常運行。
應用截圖
xml
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">
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
android:id="@+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
Activity
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) {
}
}
總結
以上是生活随笔為你收集整理的android add fragment,Android中使用FragmentTransaction对象的add方法后应用闪退的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用NHibernate 3.2实现Re
- 下一篇: 东大22春《计算机应用基础》在线平时作业