有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java一个片段在之后崩溃。添加,而另一个不添加

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

当我。在main活动中添加“BlankFragment\u frag1”,它将运行。当我。添加BlankFragment2\u fragm2,当代码退出MainActivity时,它会崩溃。onCreate方法

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

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

在主要活动中。在创建方法中,有两行:

    _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 安卓.net.Uri;
    import 安卓.os.Bundle;
    import 安卓.support.design.widget.FloatingActionButton;
    import 安卓.support.design.widget.Snackbar;
    //import 安卓.support.v4.app.Fragment;
    import 安卓.support.v4.app.FragmentTransaction;
    import 安卓.support.v4.app.FragmentManager;
    import 安卓.support.v7.app.AppCompatActivity;
    import 安卓.support.v7.widget.Toolbar;
    import 安卓.view.View;
    import 安卓.view.Menu;
    import 安卓.view.MenuItem;
    import 安卓.view.ViewGroup;
    import 安卓.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(安卓.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);
        }
    }

//空白片段。爪哇----------------------------------------

package com.example.dcornish.TestFrag;

import 安卓.content.Context;
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.support.v4.app.Fragment;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.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.安卓.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);
    }
}

//空白片段2。爪哇--------------------------------------------------

package com.example.dcornish.TestFrag;

import 安卓.content.Context;
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.support.v4.app.Fragment;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.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.安卓.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: 安卓:id = "@+id/container" -->
<!--  give id to the mainActivity layout so it can be referenced as container for fragments -->
<安卓.support.design.widget.CoordinatorLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:id = "@+id/container"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:fitsSystemWindows="true"
    tools:context="com.example.dcornish.TestFrag.MainActivity">

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

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

    </安卓.support.design.widget.AppBarLayout>

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

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

</安卓.support.design.widget.CoordinatorLayout>




  // content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:paddingBottom="@dimen/activity_vertical_margin"
    安卓:paddingLeft="@dimen/activity_horizontal_margin"
    安卓:paddingRight="@dimen/activity_horizontal_margin"
    安卓:paddingTop="@dimen/activity_vertical_margin"
    安卓:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dcornish.TestFrag.MainActivity"
    tools:showIn="@layout/activity_main">

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

//fragment_blank。xml---------------------------------------------------

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

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

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

</FrameLayout>

//fragment_blank_2。xml-------------------------------------------------

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

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

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

</FrameLayout>

//主菜单。xml-----------------------------------------------------------

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

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

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

共 (1) 个答案

  1. # 1 楼答案

    我想我可能知道是什么导致了这次坠机。添加BlankFragment2时,还必须在MainActivity中实现它的侦听器OnFragmentInteractionListener

    @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) {
    
        }
    }