本文介绍了与其他的后退按钮替换片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重写后退按钮,因为它关闭我的应用程序,当我推,我有不同的片段:


  • 片段A:指数(当我preSS后退按钮,它会关闭应用程序)

  • 片段B(当我preSS后退按钮它会回到片段A)

  • C片段(当我preSS后退按钮它会回到片段A)

和我有我的主要活动:它管理我的片段(为有一个抽屉式导航栏)

我发现这个很多帖子,但我无法实现它们:

在片段B的为例:

  @覆盖
公共无效onBack pressed(){
    FragmentManager FM = getSupportFragmentManager();
    片f = fm.findFragmentById(R.id.fragmentb); //获取当前加载占位符片段
    对象标记= f.getTag();
    //做标记的帮助在这里处理
    //调用超级方法
    super.onBack pressed();
}

它说不能解析onBack pressed()和getSupportFragmentManager(),我想我不correctely使用的方法,那么怎么办?

活动:

 进口android.app.AlertDialog;
进口android.content.DialogInterface;
进口android.graphics.Typeface;
进口android.os.Bundle;
进口android.support.v4.app.Fragment;
进口android.support.v4.app.FragmentManager;
进口android.support.v4.app.FragmentTransaction;
进口android.support.v4.widget.DrawerLayout;
进口android.support.v7.app.AppCompatActivity;
进口android.support.v7.widget.Toolbar;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.TextView;公共类MainActivity扩展AppCompatActivity实现FragmentDrawer.FragmentDrawerListener {    私有静态字符串标记= MainActivity.class.getSimpleName();
    私人工具栏mToolbar;
    私人FragmentDrawer drawerFragment;    //初始化德升AVEC激活Google莱斯最近搜索necessaires
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        mToolbar =(工具栏)findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar()setDisplayShowHomeEnabled(真)。
        drawerFragment =(FragmentDrawer)getSupportFragmentManager()findFragmentById(R.id.fragment_navigation_drawer)。
        drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout),mToolbar);
        drawerFragment.setDrawerListener(本);
        // Affichage德拉导航
        displayView(0);
    }
    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        // Ajout DES项目
        。getMenuInflater()膨胀(R.menu.menu_main,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        INT ID = item.getItemId();
        如果(ID == R.id.action_settings){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }    @覆盖
    公共无效onDrawerItemSelected(查看视图,INT位置){
        displayView(位置);
    }    私人无效displayView(INT位置){
        片段片段= NULL;
        字符串title =的getString(R.string.app_name);
        开关(位置){
            情况下0:
                片段=新ACCUEIL();
                标题=的getString(R.string.title_accueil);
                打破;
            情况1:
                片段=新NosOffres();
                标题=的getString(R.string.title_nosoffres);
                打破;
            案例2:
                片段=新DemandeGratuite();
                标题=的getString(R.string.title_demandegratuite);
                打破;
            案例3:
                片段=新ContactezNous();
                标题=的getString(R.string.title_contact);
                打破;
            情况4:
                片段=新Actualites();
                标题=的getString(R.string.title_actu);
                打破;
            情况5:
                片段=新MentionsLegales();
                标题=的getString(R.string.title_mentions);
                打破;
            默认:
                打破;
        }        如果(片段!= NULL){
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body,片段);
            fragmentTransaction.commit();
            // libelle杜工具栏
            TextView的titlet;
            titlet =(的TextView)findViewById(R.id.main_toolbar_title);
            titlet.setText(职称);
            titlet.setTypeface(Typeface.createFromAsset(getAssets(),字体/ GothamBook.ttf));
        }
    }
}

@jujyfruits

我trye​​dbut它不工作:

  @覆盖
    公共无效onBack pressed(){
        片段myFragment = getSupportFragmentManager()findFragmentById(R.id.demande_gratuite)。
        如果(myFragment =空&放大器;!&放大器; myFragment.isVisible()){
            AlertDialog alertDialog =新AlertDialog.Builder(本).create();
            alertDialog.setTitle(复位...);
            alertDialog.setMessage(测试);
            alertDialog.setButton(OK,新DialogInterface.OnClickListener(){
                公共无效的onClick(DialogInterface对话,诠释它){
                }
            });
            alertDialog.show();
        }
        super.onBack pressed();
    }
}

@AutonomousApps

 公共类MainActivity扩展AppCompatActivity实现FragmentDrawer.FragmentDrawerListener {    私有静态字符串标记= MainActivity.class.getSimpleName();
    私人工具栏mToolbar;
    私人FragmentDrawer drawerFragment;    //初始化德升AVEC激活Google莱斯最近搜索necessaires
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        mToolbar =(工具栏)findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar()setDisplayShowHomeEnabled(真)。
        drawerFragment =(FragmentDrawer)getSupportFragmentManager()findFragmentById(R.id.fragment_navigation_drawer)。
        drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout),mToolbar);
        drawerFragment.setDrawerListener(本);
        // Affichage德拉导航
        displayView(0);
    }
    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        // Ajout DES项目
        。getMenuInflater()膨胀(R.menu.menu_main,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        INT ID = item.getItemId();
        如果(ID == R.id.action_settings){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }    @覆盖
    公共无效onDrawerItemSelected(查看视图,INT位置){
        displayView(位置);
    }    私人无效displayView(INT位置){
        片段片段= NULL;
        字符串title =的getString(R.string.app_name);
        开关(位置){
            情况下0:
                片段=新ACCUEIL();
                标题=的getString(R.string.title_accueil);
                打破;
            情况1:
                片段=新NosOffres();
                标题=的getString(R.string.title_nosoffres);
                打破;
            案例2:
                片段=新DemandeGratuite();
                标题=的getString(R.string.title_demandegratuite);
                打破;
            案例3:
                片段=新ContactezNous();
                标题=的getString(R.string.title_contact);
                打破;
            情况4:
                片段=新Actualites();
                标题=的getString(R.string.title_actu);
                打破;
            情况5:
                片段=新MentionsLegales();
                标题=的getString(R.string.title_mentions);
                打破;
            默认:
                打破;
        }        如果(片段!= NULL){
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body,片段);
            fragmentTransaction.addToBackStack(名称);
            fragmentTransaction.commit();
            // libelle杜工具栏
            TextView的titlet;
            titlet =(的TextView)findViewById(R.id.main_toolbar_title);
            titlet.setText(职称);
            titlet.setTypeface(Typeface.createFromAsset(getAssets(),字体/ GothamBook.ttf));
        }
    }    @覆盖
    公共无效onBack pressed(){
        FragmentManager经理= getSupportFragmentManager();
        如果(mgr.getBackStackEntryCount()== 0){
            super.onBack pressed();
        }其他{
             mgr.popBackStack();
        }
    }


解决方案

这是什么片段之间导航,当我使用:

MainActivity.java:

  @覆盖
公共无效onBack pressed(){
    //注意:您还可以使用getSupportFragmentManager()
    FragmentManager经理= getFragmentManager();
    如果(mgr.getBackStackEntryCount()== 0){
        //没有backstack流行,因此调用超
        super.onBack pressed();
    }其他{
        mgr.popBackStack();
    }
}

编辑第二个:请注意,您只需要调用 super.onBack pressed()如果您还没有处理(通过,例如,啪片段经理backstack)。

有关的工作,你有新的片段添加到您的 FragmentManager 的backstack( addToBackStack() )。例如(也是在 MainActivity.java

 私人无效displayView(INT位置){
    片段片段= ...; //你的code HERE
    如果(片段!= NULL){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body,片段);        //添加此行
        fragmentTransaction.addToBackStack(名称); //名称可以为null        fragmentTransaction.commit();
        // libelle杜工具栏
        TextView的titlet;
        titlet =(的TextView)findViewById(R.id.main_toolbar_title);
        titlet.setText(职称);
        titlet.setTypeface(Typeface.createFromAsset(getAssets(),字体/ GothamBook.ttf));
    }
}

修改第三(7/28):的onCreate(捆绑)方法,通过调用做你的第一个片段的交易 displayView(INT)方法。 displayView(INT)总是的补充其片段交易的backstack。这是不是你想要的。非常的第一个的片段事务应该使用 fragmentTransaction。** **添加(INT,片段)和应该的的通话 addToBackStack(字符串)。每一笔交易的之后的首先应该叫 fragmentTransaction。**更换**(INT,片段)的来电 addToBackStack(字符串)。这样做的原因是,你的第一个的交易基本上是加入片段(您的UI)到一个空的容器(它不是取代另一个片段)。当这个交易是在backstack,这意味着空容器状态的的上backstack。所以,当你弹出,去年的交易,它会显示一个空白的UI。

修改第一:当你调用 addToBackStack(字符串名称) 上的对象(通过调用的),那么你是添加 FragmentTransaction 你的 FragmentManager S'backstack。我什么code的作用是通过调用尺寸的的backstack的href=\"http://developer.android.com/reference/android/app/FragmentManager.html#getBackStackEntryCount()\"相对=nofollow> getFragmentManager.getBackStackEntryCount() 。如果这个数字大于零,那么我们知道我们有 FragmentTransaction S于该backstack。在这种情况下,你可以调用,这将弹出最后交易掉backstack - 换句话说,你的应用程序返回的最后一个片段,这是展示

如果该backstack进入县城等于0,那么这意味着你在你的片段A,你应该改为调用 super.onBack pressed(),这将导致应用程序退出。

I'm trying to override the Back Button because it's closing my app when I push on, I have different Fragments:

  • Fragment A: Index (When I press back button, it's will close the app)
  • Fragment B (When I press back button it will go back to the Fragment A)
  • Fragment C (When I press back button it will go back to the Fragment A)

And I have my Main Activity: It manage my Fragments (for have a Navigation Drawer).

I found many posts on this but I can't implement them:

On Fragment B for exemple:

@Override
public void onBackPressed(){
    FragmentManager fm = getSupportFragmentManager();
    Fragment f = fm.findFragmentById(R.id.fragmentb); // get the fragment that is currently loaded in placeholder
    Object tag = f.getTag();
    // do handling with help of tag here
    // call super method
    super.onBackPressed();
}

It say cannot resolve onBackPressed() and getSupportFragmentManager(), I think I don't use the method correctely, so how to do ?

Activity:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

    private static String TAG = MainActivity.class.getSimpleName();
    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;

    //Initialisation de l activite avec les donnees necessaires
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        drawerFragment = (FragmentDrawer)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);
        // Affichage de la navigation
        displayView(0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Ajout des items
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new Accueil();
                title = getString(R.string.title_accueil);
                break;
            case 1:
                fragment = new NosOffres();
                title = getString(R.string.title_nosoffres);
                break;
            case 2:
                fragment = new DemandeGratuite();
                title = getString(R.string.title_demandegratuite);
                break;
            case 3:
                fragment = new ContactezNous();
                title = getString(R.string.title_contact);
                break;
            case 4:
                fragment = new Actualites();
                title = getString(R.string.title_actu);
                break;
            case 5:
                fragment = new MentionsLegales();
                title = getString(R.string.title_mentions);
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();
            // libelle du toolbar
            TextView titlet;
            titlet = (TextView) findViewById(R.id.main_toolbar_title);
            titlet.setText(title);
            titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
        }
    }
}

@jujyfruits

I tryedbut it doesn't work:

    @Override
    public void onBackPressed(){
        Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.demande_gratuite);
        if (myFragment != null && myFragment.isVisible()) {
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("Reset...");
            alertDialog.setMessage("test");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alertDialog.show();
        }
        super.onBackPressed();
    }
}

@AutonomousApps

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

    private static String TAG = MainActivity.class.getSimpleName();
    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;

    //Initialisation de l activite avec les donnees necessaires
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        drawerFragment = (FragmentDrawer)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);
        // Affichage de la navigation
        displayView(0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Ajout des items
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new Accueil();
                title = getString(R.string.title_accueil);
                break;
            case 1:
                fragment = new NosOffres();
                title = getString(R.string.title_nosoffres);
                break;
            case 2:
                fragment = new DemandeGratuite();
                title = getString(R.string.title_demandegratuite);
                break;
            case 3:
                fragment = new ContactezNous();
                title = getString(R.string.title_contact);
                break;
            case 4:
                fragment = new Actualites();
                title = getString(R.string.title_actu);
                break;
            case 5:
                fragment = new MentionsLegales();
                title = getString(R.string.title_mentions);
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.addToBackStack("name");
            fragmentTransaction.commit();
            // libelle du toolbar
            TextView titlet;
            titlet = (TextView) findViewById(R.id.main_toolbar_title);
            titlet.setText(title);
            titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
        }
    }

    @Override
    public void onBackPressed(){
        FragmentManager mgr = getSupportFragmentManager();
        if (mgr.getBackStackEntryCount() == 0) {
            super.onBackPressed();
        }else{
             mgr.popBackStack();
        }
    }
解决方案

This is what I use when navigating between fragments:

MainActivity.java:

@Override
public void onBackPressed() {
    // note: you can also use 'getSupportFragmentManager()'
    FragmentManager mgr = getFragmentManager();
    if (mgr.getBackStackEntryCount() == 0) {
        // No backstack to pop, so calling super
        super.onBackPressed();
    } else {
        mgr.popBackStack();
    }
}

EDIT the second: Please note that you ONLY want to call super.onBackPressed() if you haven't already handled it (by, for example, popping the fragment manager's backstack).

For that to work, you have to add new fragments to your FragmentManager's backstack (addToBackStack()). For example (also in MainActivity.java):

private void displayView(int position) {
    Fragment fragment = ...; // YOUR CODE HERE
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);

        // ADD THIS LINE
        fragmentTransaction.addToBackStack("name"); // name can be null

        fragmentTransaction.commit();
        // libelle du toolbar
        TextView titlet;
        titlet = (TextView) findViewById(R.id.main_toolbar_title);
        titlet.setText(title);
        titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
    }
}

EDIT the third (7/28): In your onCreate(Bundle) method, you do your very first fragment transaction by calling your displayView(int) method. displayView(int) always adds its fragment transactions to the backstack. This is not what you want. The very first fragment transaction should use fragmentTransaction.**add**(int, Fragment) and should not call addToBackStack(String). Every transaction after the first should call fragmentTransaction.**replace**(int, Fragment) and should call addToBackStack(String). The reason for this is that you first transaction is basically "adding" a fragment (your UI) to an empty container (it is not "replacing" another fragment). When this transaction is on the backstack, that means that the empty-container state is also on the backstack. So when you pop that last transaction, it displays a blank UI.

EDIT the first: When you call addToBackStack(String name) on a FragmentTransaction object (which you obtain by calling getFragmentManager().beginTransaction()), then you are adding a FragmentTransaction to your FragmentManagers 'backstack'. What my code does is check the size of the backstack by calling getFragmentManager.getBackStackEntryCount(). If that number is greater than zero, then we know we have FragmentTransactions on the backstack. In such a case, you can call getFragmentManager.popBackStack(), which will pop the last transaction off the backstack--in other words, returning your app to the last Fragment that was on display.

If the backstack entry county equals 0, then that means you're at your Fragment A, and you should instead call super.onBackPressed(), and this will cause the app to exit.

这篇关于与其他的后退按钮替换片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 07:16