MainActivity在按下按钮时分段并返回MainActivity

时间:2016-03-31 07:24:49

标签: android android-fragments

我有一个Mainactivity,其中包含一个布局,它是4个子布局的父级。在点击子布局时,我将找到一个替换主布局的新片段。但按下“返回”按钮后,我无法返回MainActivity

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        aboutUs = (RelativeLayout) findViewById(R.id.aboutUs);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    //click methods goes here

    public void clickAboutUs(View view){

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
        fragmentTransaction.replace(R.id.fragment_container,fragmentAboutUs);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);

        fragmentTransaction.commit();



    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

FragmentAboutUs.java

public class FragmentAboutUs extends Fragment
{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.about_us, container,false);
        return view;
    }
}

如何从片段中按回按钮后再次返回主页面。

4 个答案:

答案 0 :(得分:2)

如果您有一个活动和四个片段,请在onBackPressed()中设置MainActivity,如下所示。

@Override
        public void onBackPressed()
        {
            super.onBackPressed();
            finish();          
        }

分段:

 @Override
    public void onResume() {

        super.onResume();
        new PlayListFragment();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                    if(getFragmentManager().getBackStackEntryCount() > 0) {
                      getFragmentManager().popBackStack();
                    }

                    return true;

                }

                return false;
            }
        });
    }

答案 1 :(得分:1)

尝试这样

    public boolean popFragment() {
    boolean isPop = false;

    Fragment currentFragment = getSupportFragmentManager()
            .findFragmentById(R.id.flContent);

        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            isPop = true;
            getSupportFragmentManager().popBackStackImmediate();
        }

    return isPop;
}

@Override
public void onBackPressed() {
    if (!popFragment()) {
        finish();
    }
}

public void replaceFragment(Fragment fragment, boolean addToBackStack) {

    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();

    if (addToBackStack) {
        transaction.addToBackStack(null);

    } else {
        getSupportFragmentManager().popBackStack(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);

    }
    transaction.replace(R.id.fragment_container, fragment);
    transaction.commit();
    getSupportFragmentManager().executePendingTransactions();

}

添加上述方法是在您的父Activity中 并使用像

 FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
 replaceFragment(fragmentAboutUs , true);

答案 2 :(得分:0)

您可以覆盖MainActivity的onBackPressed

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 1) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

答案 3 :(得分:0)

以下是Xamarin

的完成方式

加载片段(我为此编写了辅助方法,但没有必要):

public void LoadFragment(Activity activity, Fragment fragment)
{
    var backStateName = fragment.GetType().Name;
    var fm = activity.FragmentManager;
    var ft = fm.BeginTransaction();

    ft.Replace(Resource.Id.mainContainer, fragment);
    ft.AddToBackStack(backStateName);

    ft.Commit();
}

后退按钮(在MainActivity中):

public override void OnBackPressed()
{
    if (isNavDrawerOpen()) drawerLayout.CloseDrawers();
    else
    {
        var backStackEntryCount = FragmentManager.BackStackEntryCount;

        if (backStackEntryCount == 1) Finish();
        else if (backStackEntryCount > 1) FragmentManager.PopBackStack();
        else base.OnBackPressed();
    }
}

isNavDrawerOpen方法:

bool isNavDrawerOpen()
{
    return drawerLayout != null && drawerLayout.IsDrawerOpen(Android.Support.V4.View.GravityCompat.Start);
}