2015-10-22 85 views
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); 

    } 
} 

回答

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(); 

驗證。新增(65,EF)的一部分。你不能添加一個隨機的int 65,它必須是容器視圖的資源id,你需要動態添加一個片段。

相關問題