Я только что создал новый проект «Blank activity». И теперь я хотел бы добавить фрагмент в backstack, нажимая кнопку, которую показывает «Blank activity». Проблема: аппликация неожиданно закрывается при нажатии кнопки.Android: пытается добавить фрагмент в backscack (проект «Blank activity»)
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);
}
}