addToBackStack与Fragments的行为很奇怪

时间:2014-01-10 18:24:57

标签: android android-fragments

当我点击某个项目时,它会打开一个新片段。当我单击返回时,它返回,但保持新片段可见。第二次单击项目将打开一个新片段。再次单击返回,它将返回到第一个打开的片段。再次单击返回关闭应用程序。

观看此视频,了解直观展示:Screen Capture

主要活动:`

package com.example.exempelfragmentsgrund;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends FragmentActivity implements MenyFragment.onMenyKnappClickListener{

        @Override
        public void onCreate (Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
System.out.println("MainActivity onCreate");
                setContentView(R.layout.activity_main);

                if (findViewById(R.id.fragment_container_liten) != null){
System.out.println("Detta är den lilla layouten!");                   
                        if (savedInstanceState != null){
                                return;
                        }

                        MenyFragment menyFragment = new MenyFragment();
                        menyFragment.setArguments(getIntent().getExtras());
                        getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, menyFragment).commit();
                }
                if (findViewById(R.id.fragment_container_liten) == null){
System.out.println("Detta är den Stora layouten");
                }
        }

        public void onMenyKnappVald (int position){
System.out.println("MainActivity onMenyKnappVald");

        VisaFragment visaFrag = (VisaFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_dold);

        if (visaFrag != null) {
                visaFrag.visaFragmentArgument(position);

        }else{
                VisaFragment nyttFragment = new VisaFragment();
                Bundle argument = new Bundle ();

                argument.putInt(VisaFragment.ARG_POSITION, position);
                nyttFragment.setArguments(argument);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, nyttFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        }


        }

}

`

0 个答案:

没有答案