addToBackStack函数在Android Studio中无法正常工作

时间:2016-09-27 06:26:26

标签: android android-fragments

我是android的新手并使用android studio 2.2 在我的应用程序中,我使用了不同的片段,当用户点击ImageView时我们会出现它们,并且我已经使用addToBackStack函数作为设备后退按钮。它将我带到前一个片段,但根据单击后退按钮时的语句不会突出显示先前的Imageview。 这是片段的代码

public void dates(View view)
{
    if(frag != null)
    {
        home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
        subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
        noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
        settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
        date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon_black));
        date.setTextColor(0xFF000000);
        getSupportActionBar().setTitle("Available Dates");
        frag = new AvailableDates();
        FragmentManager fm = getFragmentManager();

        FragmentTransaction fragmentTransaction = fm.beginTransaction();

        fragmentTransaction.replace(R.id.container1,frag);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}
public void subscription(View view)
{
    if (frag != null)
    {
        home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
        subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon_black));
        noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
        settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
        date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
        subs.setTextColor(0xFF000000);
        getSupportActionBar().setTitle("Subscriptions");
        frag = new Subscription();
        FragmentManager fm = getFragmentManager();

        FragmentTransaction fragmentTransaction = fm.beginTransaction();

        fragmentTransaction.replace(R.id.container1,frag);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

1 个答案:

答案 0 :(得分:0)

如果你想在按下时高亮/改变,你需要在你的活动中手动控制背压:

@Override
    public void onBackPressed() {

        if (getFragmentManager().getBackStackEntryCount() > 1) {
            getFragmentManager().popBackStack();
            // Now, your AvailableDates fragment resumes, you can hightlight your views again
        } else {
            super.onBackPressed();
        }
    }