0
我剛剛創建了一個新的「空白活動」項目。現在我想在按下「空白活動」顯示的按鈕時向後臺添加一個片段。問題:按下按鈕時,應用程序意外關閉。Android:試圖向後臺堆棧添加一個片段(「空白活動」項目)
Steps I have followed to create a fragment from an activity
Steps I have followed to add a fragment to the backstack
這些是我加入到空白活動項目的唯一代碼:
//MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ExampleFragment ef = new ExampleFragment();
/////// This line closes the application /////////
getFragmentManager().beginTransaction()
.add(65, ef) //65 is random number
// Add this transaction to the back stack
.addToBackStack(null)
.commit();
setContentView(R.layout.news_articles);
}
});
}
這是該片段的佈局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.tirengarfio.myapplication.ExampleFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
ExampleFragment.java
package com.example.tirengarfio.myapplication;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}