I have an application with two fragments which will not switch back to the original from the method I am using. I have a feeling this is not the way to carry out this. Where am I going wrong? My code is below.
// region GlobalVars
boolean viewLib;
// endregion
// region Init
void Init () {
viewLib = false;
}
// endregion
// region onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
Init();
// Set Initial Library Fragment
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
PlayerFragment firstFragment = new PlayerFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
// endregion
// region SwitchView
void SwitchView () {
if (viewLib = false) {
Toast.makeText(getApplicationContext(), "viewLib", Toast.LENGTH_SHORT).show();
Library();
viewLib = true;
} else {
Toast.makeText(getApplicationContext(), "!viewLib", Toast.LENGTH_SHORT).show();
Player();
viewLib = false;
}
}
//region Library
void Library() {
LibraryFragment newFragment = new LibraryFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
// endregion
//region Player
void Player() {
PlayerFragment newFragment = new PlayerFragment();
//Bundle args = new Bundle();
//args.putInt(LibraryFragment.ARG_POSITION, position);
//newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
// endregion
// endregion
// region Menu
@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_music, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_library:
SwitchView();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// endregion
Fixed My problem. I did this:
void SwitchView() {
if (!viewLib) {
Toast.makeText(getApplicationContext(), "viewLib", Toast.LENGTH_SHORT).show();
Library();
viewLib = true;
} else {
Toast.makeText(getApplicationContext(), "!viewLib", Toast.LENGTH_SHORT).show();
Player();
viewLib = false;
}
}
Seems to work fine now after fixing the mistake in the boolean test. Now all I have to do is override onBackPressed to stop the constant views
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments