我刚刚创建了一个新的“空白活动”项目。现在,我想在按下“空白活动”显示的按钮时向后台添加一个片段。问题:当按下按钮时,应用程序意外关闭。
Steps I have followed to create a fragment from an activity
Steps I have followed to add a fragment to the backstack
这是我添加到Blank Activity项目的唯一代码:
// 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);
}
}
答案 0 :(得分:1)
首先了解之间的区别 1.静态添加片段vs 2.动态添加片段。
本教程将为您提供帮助http://www.vogella.com/tutorials/AndroidFragments/article.html (请参阅教程中的5.1节和5.2节)
你也在做
getFragmentManager().beginTransaction()
.add(65, ef) //65 is random number
// Add this transaction to the back stack
.addToBackStack(null)
.commit();
验证.add(65,ef)部分。您不能添加随机int 65它必须是容器视图的资源ID,您想要动态添加片段。