从片段返回到另一个片段的按钮

Posted

技术标签:

【中文标题】从片段返回到另一个片段的按钮【英文标题】:Back Button from Fragment to an another Fragment 【发布时间】:2015-08-26 22:09:51 【问题描述】:

当我按下返回按钮时,我的应用程序正在关闭,所以我对其进行了一些研究,我发现: How to handle back button in activity 和 How to catch device back button event in android? :

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
    if (keyCode == KeyEvent.KEYCODE_BACK ) 
        //do your stuff
    
    return super.onKeyDown(keyCode, event);

但我得到:“无法解析方法 onKeyDown...”

我的片段:

public class NosOffres extends android.support.v4.app.Fragment 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.activity_nosoffres, container, false);
        TextView firstTitle = (TextView) view.findViewById(R.id.firstTitle);
        firstTitle.setText(html.fromHtml("<b>" + "<font color=#263355>RACHAT DE PR&Ecirc;TS IMMOBILIER</font>" + "</b>"));
        firstTitle.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView firstText = (TextView) view.findViewById(R.id.firstText);
        firstText.setText(Html.fromHtml("<font color=#5D5D5C>Op&eacute;ration qui permet de rassembler des cr&eacute;dits immobilier et des cr&eacute;dits &agrave; la consommation sur un seul nouveau contrat incluant une nouvelle dur&eacute;e de remboursement et une mensualit&eacute; r&eacute;duite.<br/><br/>Le financement est immobilier lorsque la part des encours immobiliers &agrave; reprendre est sup&eacute;rieure &agrave; 60% par rapport au total des capitaux &agrave; reprendre.</font>"));
        firstText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView firstDetail = (TextView) view.findViewById(R.id.firstDetail);
        firstDetail.setText(Html.fromHtml("<font color=#263355>Taux :" + "<b>" + " fixe ou r&eacute;visable" + "</b><br/>" +
                "Dur&eacute;es :" + "<b>" + " de 60 &agrave; 420 mois" + "</b><br/>" +
                "Assurance :" + "<b>" + " facultative</font>" + "</b>"));
        firstDetail.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));

        TextView secondTitle = (TextView) view.findViewById(R.id.secondTitle);
        secondTitle.setText(Html.fromHtml("<b>" + "<font color=#263355>RACHAT DE PR&Ecirc;TS CONSOMMATION</font>" + "</b>"));
        secondTitle.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView secondText = (TextView) view.findViewById(R.id.secondText);
        secondText.setText(Html.fromHtml("<font color=#5D5D5C>Op&eacute;ration qui permet de rassembler des cr&eacute;dits &agrave; la consommation sur un seul nouveau contrat incluant une nouvelle dur&eacute;e de remboursement et une mensualit&eacute; r&eacute;duite.<br/><br/>Le financement est &agrave; la consommation lorsque la part des encours immobiliers &agrave; reprendre est inf&eacute;rieure &agrave; 60% par rapport au total des capitaux &agrave; reprendre.</font>"));
        secondText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView secondDetail = (TextView) view.findViewById(R.id.secondDetail);
        secondDetail.setText(Html.fromHtml("<font color=#263355>Taux :" + "<b>" + " fixe ou r&eacute;visable" + "</b><br/>" +
                "Dur&eacute;es :" + "<b>" + " &agrave; partir de 12 mois" + "</b><br/>" +
                "Assurance :" + "<b>" + " facultative</font>" + "</b>"));
        secondDetail.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView textView =(TextView)getActivity().findViewById(R.id.main_toolbar_title);
        textView.setText(getString(R.string.title_nosoffres));
        textView.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        return view;
    

    @Override
    public void onActivityCreated(Bundle savedInstanceState) 
        super.onActivityCreated(savedInstanceState);
        ImageView formulaire = (ImageView) getView().findViewById(R.id.formulaire);
        formulaire.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.solutis.fr/demande-rachat-credit.html/#utm_source=googleplay&utm_medium=application&utm_campaign=application-solutis-android")));
            
        );
    

我不想进入这个片段:

public class Accueil extends android.support.v4.app.Fragment 

    //Lors de la creation de la vue, on va attribuer a chaque zone de texte, le texte voulu avec un type particulier (font family...)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        //placer ici le code pour connaitre la densite et la resolution de lecran
        View view = inflater.inflate(R.layout.activity_accueil, container, false);
        TextView topTextL1 = (TextView) view.findViewById(R.id.topTextL1);
        topTextL1.setText(Html.fromHtml("<font color=#263355>VOTRE EXPERT DU</font>"));
        topTextL1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView topTextL2 = (TextView) view.findViewById(R.id.topTextL2);
        topTextL2.setText(Html.fromHtml("<b>" + "<font color=#263355> REGROUPEMENT DE CR&Eacute;DITS </font>" + "</b>"));
        topTextL2.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView topTextL3 = (TextView) view.findViewById(R.id.topTextL3);
        topTextL3.setText(Html.fromHtml("<font color=#263355>EN FRANCE DEPUIS </font><font color=#EF7A05>1998</font><font color=#263355>.</font>"));
        topTextL3.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView bottomText = (TextView) view.findViewById(R.id.bottomText);
        bottomText.setText(Html.fromHtml("<font color=#5D5D5C>Un cr&eacute;dit vous engage et doit &ecirc;tre rembours&eacute;. V&eacute;rifiez vos capacit&eacute;s de remboursement avant de vous engager.</font>"));
        bottomText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        return view;
    

    //Apres creation de la vue ont va creer les evenements
    @Override
    public void onActivityCreated(Bundle savedInstanceState) 
        super.onActivityCreated(savedInstanceState);
        ImageView nosoffres = (ImageView) getView().findViewById(R.id.firstBlock);
        nosoffres.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                Fragment fragment = new NosOffres();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            
        );
        ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
        contact.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                Fragment fragment = new ContactezNous();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            
        );
        ImageView actualites = (ImageView) getView().findViewById(R.id.thirdBlock);
        actualites.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                Fragment fragment = new Actualites();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            
        );
        ImageView mentions = (ImageView) getView().findViewById(R.id.fourthBlock);
        mentions.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                Fragment fragment = new MentionsLegales();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            
        );
        ImageView formulaire = (ImageView) getView().findViewById(R.id.formulaire);
        formulaire.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.solutis.fr/demande-rachat-credit.html/#utm_source=googleplay&utm_medium=application&utm_campaign=application-solutis-android")));
            
        );
    

【问题讨论】:

ActivityFragment 中按回? 如果你使用的是系统后退按钮然后编写 onBackPressed() 方法并在你想去的地方写代码。 @Logic 在片段“NosOffres”中 @Allu 所以我把 onBackPressed 方法放在我的片段中? 看到这个链接你可能会得到解决方案***.com/questions/18190047/…***.com/questions/22552653/… 【参考方案1】:

@Override onBackPressed() 类的 FragmentActivity 方法

@Override
public void onBackPressed() 
    Log.d("back", "onBackPressed Called");

    // Do your stuff here

【讨论】:

所以我必须在这里调用我的 Accueil 片段?回到这里 是的,你必须打电话给这里。 我要启动一个FragmentActivity,如何从这个activity传递给一个fragment?【参考方案2】:

创建静态片段对象-

public static Fragment currentFragment = null;

并在 Activity/FragmentActivity 类中对其进行初始化

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
    if (keyCode == KeyEvent.KEYCODE_BACK ) 
        //do your stuff

        try
            if(currentFragemnt!=null)
            
                // do you work here respected to currentFragment
            

        
        catch(Exception e)
        
            e.printStackTrace();
        
    
    currentFragemnt = null;
    return super.onKeyDown(keyCode, event);

因此,基本活动将检测设备的 backPressed 并执行任务。 Fragment 无法检测 backPressed,只有它们所连接的 Activity 才能检测到它。

并将 setOnClickListener 更改为-

nosoffres.setOnClickListener(new View.OnClickListener() 
            public void onClick(View v) 
                currentFragment = new NosOffres();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            
        );

【讨论】:

但我想从 NosOffres 类回到 Accueil 类。我将您的代码放在我的 Fragment Activity 上,我没有收到任何错误,但是如何从一个活动返回到另一个活动? 什么是 CurrentFragment ? 我无法保留片段并执行 if (fragment != null) ... ? 不,我做了:Fragment fragment = new NosOffres();... 你说:currentFragment = new NosOffres();但我为什么要改名? 好吧,做我想做的,你知道如何从我的活动中调用片段吗?

以上是关于从片段返回到另一个片段的按钮的主要内容,如果未能解决你的问题,请参考以下文章

从一个片段移动到另一个片段时如何自动选择底部导航?

在活动中使用 OnBackPressed 方法的一个片段到另一个片段

当我尝试在片段中显示或隐藏浮动操作按钮时出错

onDetach()不要求从一个片段移动到另一个片段

从列表视图中删除一行后刷新片段

如何在kotlin中从一个片段转到另一个片段?