一个片段在.add之后崩溃而另一个片段没有崩溃

时间:2016-04-18 17:55:02

标签: java android

我一直试图让片段工作,但行为不一致,很难调试。我用xml文件和类文件创建了两个片段。据我所知,这两个碎片以完全相同的方式实现。

当我在MainActivity中添加“BlankFragment _frag1”时,它会运行。当我.add BlankFragment2 _frag2时,它会在代码退出MainActivity.onCreate方法时崩溃。

我在一个更复杂的应用程序中遇到了这个问题,所以我剥离了所有无关的东西并用最简单的应用程序实现它......仍然会发生。

我在下面附加了.java文件和.xml文件。我会包含整个项目的zip,但我没有看到附件文件对话框。如果有人在darrylctx@gmail.com向我提出请求,我可以通过电子邮件发送项目。

在MainActivity.onCreate方法中,有两行:

    _ft.add(R.id.container, _frag1);
    _ft.add(R.id.container, _frag2);

如果我评论_ft.add(R.id.container,_frag2); 并取消注释//_ft.add(R.id.container,_frag1);然后运行正常。 也就是说,_frag1运行正常。

如果我评论_ft.add(R.id.container,_frag1); 并取消注释_ft.add(R.id.container,_frag2);它从onCreate方法退出时崩溃。也就是说,_frag2不会运行。

据我所知,frag1和frag2的实现没有区别,但我必须遗漏一些东西。

// MainActivity.java ------------------------------------------------------------


 package com.example.dcornish.TestFrag;

    import android.net.Uri;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    //import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.app.FragmentManager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.ViewGroup;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
        BlankFragment _frag1 = new BlankFragment();
        BlankFragment2 _frag2 = new BlankFragment2();
        FragmentManager _fm;
        FragmentTransaction _ft;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

            setSupportActionBar(toolbar);
            // get the viewgroup for this activity
            ViewGroup view = (ViewGroup) findViewById(android.R.id.content);

            //Fragment Help:  add fragment to main activity
            if (savedInstanceState == null) {
                //getSupportFragmentManager().beginTransaction().add(R.id.container, new BlankFragment()).commit();
                _fm = getSupportFragmentManager();
                _ft = _fm.beginTransaction();
                // comment out one or the other of the _ft.add methods below to change fragments
                //_ft.add(R.id.container, _frag1);
                _ft.add(R.id.container, _frag2);
                _ft.commit();
            }

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
        }

        public void onFragmentInteraction(Uri uri){
            Toast toast = Toast.makeText(this, "Wheeee!",Toast.LENGTH_SHORT);
            toast.show();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

// BlankFragment.java ----------------------------------------

package com.example.dcornish.TestFrag;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link BlankFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment implements Button.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private Button mButton; //Add at the top of the fragment

    public BlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_blank, container, false);
        View view = null;
        view = inflater.inflate(R.layout.fragment_blank, container, false);
        mButton = (Button) view.findViewById(R.id.button);
        mButton.setOnClickListener(this);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    //Fragment Help:  Have to figure out what mListener.onFragmentInteraction(null) does
    public void onClick(View v){
        //Nothing here yet
        mListener.onFragmentInteraction(null);
    }
}

// BlankFragment2.java ------------------------------------------ --------

package com.example.dcornish.TestFrag;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link BlankFragment2.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BlankFragment2#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment2 extends Fragment implements Button.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private Button _button;

    public BlankFragment2() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment2.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment2 newInstance(String param1, String param2) {
        BlankFragment2 fragment = new BlankFragment2();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = null;
        view = inflater.inflate(R.layout.fragment_blank_2, container, false);
        _button = (Button) view.findViewById(R.id.whee_button);
        _button.setOnClickListener(this);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void onClick(View v){
        //Nothing here yet
        mListener.onFragmentInteraction(null);
    }
}

// activity_main.xml ------------------------------------------ -----------

 
<!--  fragment instructions: android:id = "@+id/container" -->
<!--  give id to the mainActivity layout so it can be referenced as container for fragments -->
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id = "@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.dcornish.TestFrag.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>




  // content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dcornish.TestFrag.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

// fragment_blank.xml ------------------------------------------ ---------

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dcornish.TestFrag.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Whee"
        android:id="@+id/button"
        android:layout_gravity="center" />

</FrameLayout>

// fragment_blank_2.xml ------------------------------------------ -------

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BlankFragment2">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TrajMgr"
        android:id="@+id/whee_button"
        android:layout_gravity="center" />

</FrameLayout>

// menu_main.xml ------------------------------------------ -----------------

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.dcornish.TestFrag.MainActivity">
    <item
        android:id="@+id/mnu_edit_profile"
        android:orderInCategory="100"
        android:title="Edit Profile"
        app:showAsAction="never" />
    <item
        android:id="@+id/mnu_load_profile"
        android:orderInCategory="100"
        android:title="Load Profile"
        app:showAsAction="never" />
    <item
        android:id="@+id/mnu_save_profile"
        android:orderInCategory="100"
        android:title="Save Profile"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/mnu_help"
        android:orderInCategory="100"
        android:title="Help"
        app:showAsAction="never" />
    <item
        android:id="@+id/mnu_dash1"
        android:orderInCategory="100"
        android:title="------------"
        app:showAsAction="never" />

    <item
        android:id="@+id/mnu_exit"
        android:orderInCategory="100"
        android:title="Exit"
        app:showAsAction="never" />

    <item
        android:id="@+id/mnu_test"
        android:orderInCategory="100"
        android:title="Test"
        app:showAsAction="never" />
</menu>

1 个答案:

答案 0 :(得分:0)

我想我可能会看到导致崩溃的原因。当您添加BlankFragment2时,您还需要在OnFragmentInteractionListener

中实现它的监听器MainActivity
@Override
public void onFragmentInteraction(Uri uri) {

}

看起来应该是这样的

public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener, BlankFragment2.OnFragmentInteractionListener {
    BlankFragment _frag1 = new BlankFragment();
    BlankFragment2 _frag2 = new BlankFragment2();
    FragmentManager _fm;
    FragmentTransaction _ft;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        // get the viewgroup for this activity
        ViewGroup view = (ViewGroup) findViewById(android.R.id.content);

        //Fragment Help:  add fragment to main activity
        if (savedInstanceState == null) {
            //getSupportFragmentManager().beginTransaction().add(R.id.container, new BlankFragment()).commit();
            _fm = getSupportFragmentManager();
            _ft = _fm.beginTransaction();
            // comment out one or the other of the _ft.add methods below to change fragments
//            _ft.add(R.id.container, _frag1);
            _ft.add(R.id.container, _frag2);
            _ft.commit();
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}