应用程序在主要活动中关闭onBackPressed

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了应用程序在主要活动中关闭onBackPressed相关的知识,希望对你有一定的参考价值。

您好我是片段新手..我有一个主要活动和两个片段。如果我在第一个片段的editText中输入数据,它将显示在第二个片段的TextView上。如果我输入数据并重复按下提交按钮,数据也会在第二个片段中更改..但是当我按下后退按钮时,应用程序将关闭。当我按下后退按钮时,我想要显示我先前在片段中输入的数据

这是代码:

FirstFragment extends Fragment {

    private OnFragmentInteractionListener mListener;
    private EditText inputName;
    private EditText inputPhone;
    private String userName;
    private String userPhone;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);

        inputName = (EditText) view.findViewById(R.id.edit_text_name);
        inputPhone = (EditText) view.findViewById(R.id.edit_text_phone);
        TextView submit = (TextView) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputName.getText().toString().equals("")) {
                    Toast.makeText(getActivity(), "Name must be filled", Toast.LENGTH_LONG).show();
                    return;
                }
                else if(inputPhone.getText().toString().equals("")){
                    Toast.makeText(getActivity(),"please enter the phone number" , Toast.LENGTH_SHORT).show();
                    return;
                }
                userName = inputName.getText().toString();
                userPhone = inputPhone.getText().toString();
                onButtonPressed(userName, userPhone);
                inputName.setText("");
                inputPhone.setText("");
            }
        });
        return view;
    }

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


    @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(String nameContent, String phoneContent);
    }
}

SecondFragment extends Fragment {

    //private OnFragmentInteractionListener mListener;
    private TextView updateName;
    private TextView updatePhone;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_second, container, false);
        updateName = (TextView)view.findViewById(R.id.text_view_name);
        updatePhone = (TextView)view.findViewById(R.id.text_view_phone);
        return view;
    }
    public void updateTextField(String name, String phone){
        updateName.setText(name);
        updatePhone.setText(phone);
        }
}


MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener{

    private FragmentActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public void onFragmentInteraction(String nameContent, String phoneContent) {
        SecondFragment secondFragment = (SecondFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_show);
        secondFragment.updateTextField(nameContent, phoneContent);

    }


    public FragmentActivity getActivity() {
        return activity;
    }
}


**fragment_first.xml**

<android.support.constraint.ConstraintLayout 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"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <EditText
        android:id="@+id/edit_text_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_name"
        android:inputType="text"
        android:paddingEnd="5dp"
        android:paddingStart="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintLeft_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/edit_text_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_phone"
        app:layout_constraintTop_toBottomOf="@+id/edit_text_name"
        android:inputType="phone"
        android:paddingTop="25dp"
        android:paddingStart="5dp"
        android:paddingEnd="5dp"/>

    <TextView
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/edit_text_phone"
        android:layout_marginTop="50dp"
        android:padding="7dp"
        android:text="@string/sbmt"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@drawable/button_stroke"/>



</android.support.constraint.ConstraintLayout>

**fragment_Second.xml**
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="30sp"
        android:textColor="@color/colorPrimaryDark"/>

    <TextView
        android:id="@+id/text_view_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/text_view_name"
        android:textSize="20sp"
        android:padding="8dp"
        android:textColor="@color/colorPrimary"/>

</android.support.constraint.ConstraintLayout>

activity_main.xml

<android.support.constraint.ConstraintLayout 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"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <fragment
        android:id="@+id/fragment_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.FirstFragment"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <fragment
        android:id="@+id/fragment_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.SecondFragment"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/fragment_input"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
答案

覆盖MainActivity中的“onBackPressed”方法

 @Override
public void onBackPressed()
{
  if(want_to_close_the_app){
//call super
  super.onBackPressed();
}
else{
// dont call super
}

}

另一答案

添加片段标记时添加它们。防爆。 FirstFragment的标签是“firstFragment”,SecondFragment的标签是“secondFragment”。在您的活动中获取一个名为current fragment的常见String变量,并在添加片段时更改它。

public class MainActivity extends Activity{
    public static String currentFragment = null;
    //while adding first fragment
    currentFragment = "firstFragment";

    //while adding second fragment
    currentFragment = "firstFragment";
}

现在在您的活动中覆盖onBackPressed,如下所示。

@Override
public void onBackPressed() {
    if(currentFragment.equals("secondFragment"){
        //load first fragment
    }else{
        super.onBackPressed();
    }
}
另一答案

覆盖onBackPressed方法。

@Override
public void onBackPressed()
{
super.onBackPressed();// remove this line
...
//enter your code here.
}

并添加此代码。

getSupportFragmentManger().
beginTransaction().
replace().
addToBackStack().
.commit();

以上是关于应用程序在主要活动中关闭onBackPressed的主要内容,如果未能解决你的问题,请参考以下文章

Android:如何从活动活动中关闭前台活动?

如何从通知中关闭应用程序

如何从另一个活动或底部工作表对话框/片段中关闭一个活动

什么时候在Android中关闭光标?

如何在 Kotlin 中关闭 Android 应用程序

如何在c#中关闭xmldocument