我有一个名为MainActivity的活动,带有2个片段(让他们称之为A和B)。如果是大显示,此活动在左侧显示A,在右侧显示B,但是,对于小型显示,只有一个frameLayout,并且在我单击片段B中的内容后更改其中的片段。
因此,对于小型设备,我最初显示片段A,然后我可以转到B,(我从片段A中的CalendarView中选择一天,然后我可以转到B)。
在B中,我可以通过单击按钮转到另一个活动。从那次活动开始,我想回到以前的活动,但我不知道如何让片段B已经膨胀。现在如果我回到我的MainActivity,如果我在B充气的情况下离开这个活动,我也会发现片段A.
我可以通过操作栏上的后退按钮或者在我关闭我的最后一个活动(我在B之后去的那个)后回来。
谁能帮我?
这是我有两个片段的Main活动类。
public class MainActivity extends AppCompatActivity implements CalendarFragment.OnCalendarSelectedListener{
private ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getSupportActionBar();
if(findViewById(R.id.left_fragment) != null){
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
AFragment leftFragment = new AFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.left_fragment, leftFragment).commit();
}
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.right_fragment) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
BFragment bFragment = new BFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.right_fragment, bFragment).commit();
}
}
...
//this is how I inflate the fragment B from a click on fragment A
public void onCalendarSelected(int day, int month, int year) {
BFragment bFragment = (BFragment)
getSupportFragmentManager().findFragmentById(R.id.right_fragment);
if (bFragment != null) {
bFragment.updateList(day);
} else {
actionBar.setDisplayHomeAsUpEnabled(true);
BFragment newFragment = new BFragment();
Bundle args = new Bundle();
args.putInt("day",day);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.left_fragment, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
此代码工作正常,但我不知道如何解决我的问题。