I am using Action Bar Sherlock fragments for my application. I need to go to fragment from activity. But sliding menu is not working when I goes to fragment by using this code.
Activity Code
Intent notificationIntent = new Intent(context,FragmentOpenActivity.class);
FragmentOpenActvity is like
public class FragmentOpenActivity extends SherlockFragmentActivity {
private Bundle i_fragment;
private String messages = null;
private String coupons = null;
private String yo = null;
private String invitation = null;
private String loyalty = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(android.R.id.content, new MessagesFragment()).commit();
i_fragment = getIntent().getExtras();
if (i_fragment == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new ProfileEditorFragment())
.commit();
} else {
messages = i_fragment.getString("Message");
coupons = i_fragment.getString("Coupon");
}
if (messages != null && messages.equalsIgnoreCase("Message")) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new MessagesFragment())
.commit();
} else if (coupons != null && coupons.equalsIgnoreCase("Coupon")) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new CouponsFragment())
.commit();
} else {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new ProfileEditorFragment())
.commit();
}
}
}
/**
* #return Displaying Action Bar Button with Image
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
/**
* #return Click Events for Action Bar Buttons
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
startActivity(new Intent(this, FragmentChangeActivity.class));
break;
}
return true;
}
/**
* #return Handling Back button
*/
public void onBackPressed() {
startActivity(new Intent(this, FragmentChangeActivity.class));
finish();
}
}
Please refer the following code for fragment
public class CouponsFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getSherlockActivity().getSupportActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM);
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(
true);
return inflater.inflate(R.layout.listview_refreshable, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onStart() {
super.onStart();
}
}
Normally sliding menu works perfectly but when i came from FragmentOpenActivity it is not responding. Please try to find me a solution
Related
I implemented backstack navigation on Back button in MainActivity (which have many fragments) using onBackPressed(). I want to implement same backstack navigation on Up button press. Problem is I only want Up button in one fragment but the Up button appears on every fragment when I press Up button on desired fragment. Even setDisplayHomeAsEnabled(false) is not working. How to have Up button in one fragment only?
Desired Fragment:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Main Activity
public class HomePage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
if (findViewById(R.id.fragment_place) != null) {
if (savedInstanceState != null) {
return;
}
HomeFrag firstFragment = new HomeFrag();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_place, firstFragment).commit();
}
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
} */
public void selectFrag(View view) {
Fragment fr = null;
if (view == findViewById(R.id.home_btn)) {
fr = new HomeFrag();
} else if (view == findViewById(R.id.search_btn)) {
fr = new SearchFrag();
} else if (view == findViewById(R.id.log_btn)) {
fr = new LogFrag();
} else if (view == findViewById(R.id.events_btn)) {
fr = new EventFrag();
} else if (view == findViewById(R.id.profile_btn)) {
fr = new ProfileFrag();
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr).addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
}
I created a sample application on GitHub to solve such backstack problem.
Download Fragment Back Stack application
I've been searching and thinking how to implement the desire behaviour that I want when switching back and forth between fragments when using a Navigation Drawer. Actually the documentation says:
When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen
So in my app I have a MainActivity that controls everything and a navigation layout within you can change between predefined options. This is the view when you launch the app
When you click on an item in the navigation drawer it opens a new fragment that replaces the main_content as follows:
At this point the behaviour is the correct one, so if you want to change the options you need to open the navigation drawer again to toggle between the menu options.
This is the Main Activity (notice that there is no Drawer Toggle)
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
setToolbar(); // Set Toolbar como action bar
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
// Poner ícono del drawer toggle
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
}
I don't use the hamburger icon because it hides under the Navigation Layout, but here is the thing. When you click on "Recetas" in the recycle view it open a new fragment (replace) but now I want to show the up caret icon and give proper back navigation to my app.
Here is the code of the "Consejos" fragment class
Consejos.java
public class ConsejosFragment extends Fragment {
RecyclerView mRecycler;
ConsejosAdapter mAdapter;
FragmentActivity mActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = (FragmentActivity) activity;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List items = new ArrayList();
items.add(new ConsejosInfo("Recetas", R.drawable.icon_recetas));
/* Inflamos el layout */
View v = inflater.inflate(R.layout.consejos_layout_recycler, container, false);
/* Obtenemos el Recycle */
mRecycler = (RecyclerView) v.findViewById(R.id.recycler_consejos);
/* Creamos el adaptador */
mAdapter = new ConsejosAdapter(mActivity, items);
/* Set click en adapter */
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
}
}
And this is the adapter that the Recyclerview use and handles the click on the item inside:
Adapter.java
public class ConsejosAdapter extends RecyclerView.Adapter<ConsejosAdapter.ConsejosViewHolder> {
private List<ConsejosInfo> _items = new ArrayList<ConsejosInfo>();
private final FragmentActivity mActivity;
private Context context;
public ConsejosAdapter(FragmentActivity mActivity, List<ConsejosInfo> items) {
this._items = items;
this.mActivity = mActivity;
}
#Override
public int getItemCount() {
return _items.size();
}
#Override
public ConsejosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_consejos, viewGroup, false);
return new ConsejosViewHolder(v);
}
#Override
public void onBindViewHolder(ConsejosViewHolder viewHolder, int position) {
viewHolder.imagen.setImageResource(_items.get(position).get_imagen());
viewHolder.nombre.setText(_items.get(position).get_nombre());
}
public class ConsejosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imagen;
public TextView nombre;
public ConsejosViewHolder(final View itemView) {
super(itemView);
imagen = (ImageView) itemView.findViewById(R.id.consejos_imagen);
nombre = (TextView) itemView.findViewById(R.id.consejos_nombre);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
RecetasFragment recetasFragment = new RecetasFragment();
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, recetasFragment)
.addToBackStack(null)
.commit();
}
}
}
In the Consejos Adapter I added to backstack the fragment before calling the new fragment (inside fragment) and that changes the behaviour of the back button, so before this if you press the back button is closes the app but now it takes you to the Consejos fragment, but now I want to add the up caret and make the exactly same operation as when you click the back button but I don't know how to achieve it.
Please feel free to ask for more code
Thank you very much
I will give you the full answer:
We will use the interfaces to communicate with the MainActivity from RecetasFragment so we can enable and disable navigation back button.
RecetasFragment class:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by hema on 8/19/2015.
*/
public class RecetasFragment extends Fragment {
private CommunicateWithActivity mWithActivity;
public RecetasFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mWithActivity = (CommunicateWithActivity) activity; // MainActivity must implement CommunicateWithActivity interface.
mWithActivity.enableNavigationBack(true); // We enable navigation back here.
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CommunicateWithActivity");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recetas, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mWithActivity.enableNavigationBack(false); // We disable navigation back here, restore menu icon.
}
public interface CommunicateWithActivity {
void enableNavigationBack(boolean enable);// we will implement this method in MainActivity class.
}
}
And in MainActivity class we will implement CommunicateWithActivity interface, Modify your MainActivity class (only required modifications):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements RecetasFragment.CommunicateWithActivity {
private Toolbar mToolbar;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
#Override
public void enableNavigationBack(boolean enable) {
if(enable) {
// We enable the navigation back button here
mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// On navigation back button clicked.
if(getSupportFragmentManager().getBackStackEntryCount() > 0) { // Check if there is fragments in BackStack.
getSupportFragmentManager().popBackStack(); // PopBackStack.
} else {
// You can implement this part as you want.
return;
}
}
});
} else {
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(drawerLayout != null) {
drawerLayout.openDrawer(Gravity.LEFT);
}
}
});
}
}
}
Please let me know if there is something you don't understand.
For some reason the overflow dots do not appear on my tablet for my master detail application when I select a list item but yet they do on my handset. I'm not sure why is occurring despite using the necessary code. Does anyone there is any code missing or that shouldn't be there?
MainActivity.java
public class MainActivity extends ActionBarActivity {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch (Exception e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getResources().getString(R.string.greeting));
FragmentMainList newFragment = new FragmentMainList();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
}
}
Activity Class
public class MyProductActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_fragment);
if (savedInstanceState == null) {
FragmentProduct newFragment = new FragmentProduct();
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
ActionBar actionBar = getSupportActionBar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
final Intent intent = NavUtils.getParentActivityIntent(this);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
NavUtils.navigateUpTo(this, intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment Class
public class FragmentProduct extends android.support.v4.app.Fragment {
public FragmentProduct() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_product, container, false);
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
final Intent intent = NavUtils.getParentActivityIntent(getActivity());
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
NavUtils.navigateUpTo(getActivity(), intent);
return true;
}
int id = item.getItemId();
if (id == R.id.action_options) {
}
return super.onOptionsItemSelected(item);
}
}
The dots will be shown only for devices which don't have hardware Menu button. For devices with a hardware Menu button no overflow dots are shown since tapping on the menu button will do the same.
For more here
Edit
If for some reason you really want to show it, you can add below code in your Application.onCreate() or main (launcher) activity onCreate()
// force show actionbar 'overflow' button on devices with hardware menu button
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch (Exception e) {
e.printStackTrace();
}
Before I post, I tried to read many topics about restore app state and tried it but it does not solve my problem.
My Class is:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private static boolean lv11 = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
if(position == 0)
{
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
else if(position == 1)
{
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceProfile.newInstance(position + 1))
.commit();
}
else if(position == 2)
{
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceLogBook.newInstance(position + 1))
.commit();
}
else if(position == 3)
{
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceBeverages.newInstance(position + 1))
.commit();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
boolean finInfo = data.getBooleanExtra("Done", false);
System.out.println("OnActivityResult = " + finInfo);
if (finInfo == true) {
readIt.setBackgroundColor(R.drawable.abc_ab_bottom_solid_light_holo);
if (readIt.getText() == info1.getText()) {
lv11 = false;
}
}
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
InitializeItem();
if(savedInstanceState != null) {
Log.v("","on Creat View");
lv11 = savedInstanceState.getBoolean("Level1");
if (lv11 == false) {
info1.setBackgroundColor(R.drawable.abc_ab_bottom_solid_light_holo);
}
}
//where i create my view ...
return rootView;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.v("TAG", "In frag's on save instance state ");
savedInstanceState.putBoolean("Level1",false);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
All are working fine but my problem is using onSaveInstantState() method.I used Log.v to check and it called when I press recent button on hardware then I kill it.After that when I run the app again my SaveInstantstate is null.In my case I want to change button color by check boolean that put parameter in save state and restore it back on onCreateView.
I want to know:
what is wrong in my implementation and why I can't call restore my state
How to implement it in the right way
*all code above are in the same class file
Thank you,and sorry for my grammar.
After you killed your application, all you Bundles are destroyed. The onSavedInstanceState() is used to protect state of app from being killed by the OS.
In your case you need to save the state permanently.
The "SharedPreferences" is ideal for that.
I am using sherlock library. My problem is i am unable to change fragments on different button clicks.
Here is my code:
public class AmecmainActivity extends FragmentActivity {
private ImageButton legislativebutton;
private ImageButton About;
private ImageButton OutageReport;
private ImageButton ViewPageReportLeft;
private ImageView ViewPageReportRight;
private ImageButton actionnetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amecmain);
actionnetwork=(ImageButton)findViewById(R.id.Actionnetwork);
actionnetwork.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("action", "actionnetwork");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
ViewPageReportLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("html", "htmlcontent");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
In this I'm using a common functionality
public class FragmentChangeActivity extends SlidingFragmentActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
Bundle b = in.getExtras();
String name= b.getString("action");
//Here i am getting the values through intent so that i can give that name
// set the fragment.
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(b, "action");
if (mContent==name)// Here i am setting fragments i dnot know to check the
// condition here mContent is fragment and i am giving
// string how to check the condition.
mContent = new Fragment1(); //here i am setting fragment
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment()).commit();
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) // Here is switchcontent method which
// will change the fragment content
{
mContent = fragment;
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menuIcon:
toggle();
break;
case android.R.id.home:
getFragmentManager().executePendingTransactions();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
}