简体   繁体   English

从片段关闭应用程序会导致返回到父活动

[英]Closing the application from a fragment causes returning to the parent activity

I tried several ways to end application from inside of a fragment, like:我尝试了几种方法来从片段内部结束应用程序,例如:

system.exit(1)
android.os.Process.killProcess(android.os.Process.myPid());
getActivity().finish();

and it is all of fragment code;Exit code put on exitDialog.setPositiveButton oncliklistener that in my try cuse backing to parent activity instead exit它是所有的片段代码;退出代码放在 exitDialog.setPositiveButton oncliklistener 上,在我的尝试中使用支持父活动而不是退出

package com.TB.mylistprojct;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class ActFooter extends Fragment
{
    View            EMyView         =null;

    Button          BtnExit         =null;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater Inflater,ViewGroup Container,Bundle SavedInstanceState)
{
    View MyView=Inflater.inflate(R.layout.actfooter, Container,false);
    EMyView=MyView;
    InitialUI();
    return MyView;
}

public void InitialUI()
{
    BtnExit=(Button)EMyView.findViewById(R.id.Btn_exit);
    BtnExit.setOnClickListener(BtnExit_OnClick);
}

public OnClickListener BtnExit_OnClick=new OnClickListener()
{

    @Override
    public void onClick(View arg0)
    {
        AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());

        exitDialog.setTitle("Warning");
        exitDialog.setMessage("Exit Program");
        exitDialog.setPositiveButton("YSE", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                // Exit Code PUT Here
            }
        });
        exitDialog.setNegativeButton("NO", null);
        exitDialog.show();
    }
};
}

But the app returns to the parent activity但是应用程序返回到父活动

try this:试试这个:

getActivity().moveTaskToBack(true); 
getActivity().finish();

Finally i find the solution最后我找到了解决方案

first i add fllowing code in fragment首先我在片段中添加流动代码

Intent intent = new Intent(getActivity(), ACTMain.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("LOGOUT", true);
                startActivity(intent);

                getActivity().finish();

and in main activity(in onCreate function) i check status with if statement and exit :)在主要活动中(在 onCreate 函数中)我使用 if 语句检查状态并退出 :)

        if (getIntent().getBooleanExtra("LOGOUT", false))
    {
        finish();
    }

Recently I was having the same issue with my app.最近我的应用程序遇到了同样的问题。 I used two exit button one in main activity other one in a fragment我在主要活动中使用了两个退出按钮,另一个在片段中

For main activity:- first I create a button in main activity.xml file with onClick attributes then in java I used:对于主要活动:-首先我在 main activity.xml 文件中创建一个带有 onClick 属性的按钮,然后在我使用的 Java 中:

Inside MainActivity.java:在 MainActivity.java 中:

For Fragment:- I use setOnClickListener : Inside HomeFragment.java:对于片段:- 我使用setOnClickListener :在 HomeFragment.java 中:

Below is the code which works for me for fragment inside MainActivity.java下面是适用于我MainActivity.java 中的片段的代码

public void clickExit(View v){
finish();
}

inside Fragment.javaFragment.java 中

button_2=(Button) view.findViewById(R.id.home_exit_btn);
    button_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Closing application...",   Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        });
        return view;
    }

This work very well for me (all go in the Activity that have the fragment container):这对我来说非常有效(都在具有片段容器的 Activity 中):

private void backStack(){
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        getSupportFragmentManager().popBackStack();
    }else
    if(getSupportFragmentManager().getBackStackEntryCount()==1){
        this.finish();
    }
}

you must use this code in here:您必须在这里使用此代码:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    boolean back = false;
    if(keyCode == KeyEvent.KEYCODE_BACK){
        back = true;
        backStack();
    }
    return back;

}

The app will only exit if there are no activities in the back stack.仅当返回堆栈中没有活动时,应用才会退出。 So, add android:noHistory="true" to all the activities(which you don't want to be back stacked) in your manifest file.因此,将android:noHistory="true"到清单文件中的所有活动(您不希望将其反向堆叠)。 And, then to close the app call the finish() in the OnBackPressed() method.而且,然后关闭应用程序调用finish()OnBackPressed()方法。

<activity 
    android:name=".activities.MainActivity" 
    android:noHistory="true" />

you can use .....你可以使用......

if(keyCode == KeyEvent.KEYCODE_BACK)
{
   getActivity().moveTaskToBack(true);
}

Apart from :除了:

getActivity().finish()

This also worked for me :这也对我有用:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

I had the same problem today and i tried this code and it worked fine for me and i hope will word for everyone.我今天遇到了同样的问题,我尝试了这段代码,它对我来说很好用,我希望对每个人都能说出来。

put this code in fragment
Intent intent = new Intent(fragment_name.this, MainActivity_name.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("LOGOUT", true);
            startActivity(intent);
            fragment_name.this.finish();

and put this code inside onCreate function并将此代码放在 onCreate 函数中

    if (getIntent().getBooleanExtra("LOGOUT", false))
        {
            finish();
            System.exit(0);
        }

thanks to @HamidTB :)感谢@HamidTB :)

You Just need to hold the instance of the parent activity in your fragment to call it's functions like in this case function is to close the app so just in your fragment type你只需要在你的片段中保存父活动的实例来调用它的函数,就像在这种情况下函数是关闭应用程序所以只是在你的片段类型中

syntax is -> referencesObj = activity cast as "parentClass"

kotlin -> val parentActivity = activity as MainActivity
Java   -> MainAcitivity parentAcitivity = (MainActivity) getActivity();

and then just use it's function like finish():然后只需使用它的功能,如完成():

parentActivity.finish()

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM