In my app I have created a Navigation Drawer with six Fragments. The MainOption Fragment is not included in the Navigation item menu list. Now I want to activate Back button on mobile device to redirect to Main Fragment. For example if I have fragments A,B,C,D,E,F, and now if I click B, then if I press back button, it will back to A. In the same way if I Press back button on Fragment E it will redirect to Fragment A. Now how can I achive this logic in my code. Hence I have tried lots of code from the website, but nothis was working at all. Here is my code snepet for Navigation Drawer
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private Toolbar toolbar ;
private View navigationHeader;
private ImageView imgProfile;
private TextView txtName, txtWebsite;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navigationHeader= navigationView.getHeaderView(0);
txtName = navigationHeader.findViewById(R.id.username);
txtWebsite = navigationHeader.findViewById(R.id.email);
imgProfile = navigationHeader.findViewById(R.id.profile_image);
// load nav menu header data
loadNavHeader();
//Set the Home Fragment initially
OptionMenuFragment fragment = new OptionMenuFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
fragmentTransaction.commit();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void loadNavHeader() {
// name, website
txtName.setText("Hallo");
txtWebsite.setText("mail.com");
imgProfile.setImageResource(R.drawable.profile_image);
//ToDo: Image should be uploaded from web
}
String lastFragmentTag;
boolean showingFirstFragment = true;
public void addNewFragment(Fragment fragment, String fragmentTag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (lastFragmentTag != null) {
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
} else {
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
transaction.hide(currentFragment);
}
transaction.add(R.id.fragment_container, fragment, fragmentTag);
transaction.commit();
lastFragmentTag = fragmentTag;
showingFirstFragment = false;
}
#Override
public void onBackPressed() {
//Here we're gonna remove the last fragment added, and show OptionMenuFragment again
if (!showingFirstFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
transaction.show(firstFragment);
transaction.commit();
showingFirstFragment = true;
} else {
super.onBackPressed();
}
}
#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.blu_home) {
Intent intent = new Intent(this, MainOptionPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
String fragmentTag=null;
// Handle navigation view item clicks here.
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.view_profile:
fragment = new ViewProfileFragment();
fragmentTag = "ViewProfileFragment";
break;
case R.id.todo_list:
fragment =new ToDoListFragment();
fragmentTag="ToDoListFragment";
break;
case R.id.logout:
showAlertDialogLogOut();
break;
case R.id.settings:
fragment = new SettingsFragment();
fragmentTag="SettingFragment";
break;
case R.id.about:
fragment = new AboutFragment();
fragmentTag="AboutFragment";
break;
case R.id.info:
fragment=new InfoFragment();
fragmentTag="InfoFragment";
break;
}
if(fragment!=null){
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void showAlertDialogLogOut() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Logout");
builder.setMessage("Are you sure you want to log out?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
dialog.dismiss();
startActivity(new Intent(MainOptionPage.this, LoginPage.class));
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
For that approach, you will want to use the add(containerViewId, fragment, tag) method instead of replace(containerViewId, fragment), since replace will call remove(Fragment) for ALL fragments previously added to the container, before adding the new fragment. Also, you will want to use addToBackStack(name).
Here's a method I created for a project, and slightly modified for you:
String lastFragmentTag;
boolean showingFirstFragment = true;
public void addNewFragment(Fragment fragment, String fragmentTag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (lastFragmentTag != null) {
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
} else {
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
transaction.hide(currentFragment);
}
transaction.add(R.id.fragment_container, fragment, fragmentTag);
transaction.commit();
lastFragmentTag = fragmentTag;
showingFirstFragment = false;
}
Then you just have to make this change inside onNavigationItemSelected:
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
String fragmentTag;
switch (item.getItemId()) {
case R.id.view_profile:
fragment = new ViewProfileFragment();
fragmentTag = "ViewProfileFragment";
break;
...
}
if(fragment!=null){
addNewFragment(fragment, fragmentTag);
}
Where "fragmentTag", is going to be a String variable which you change according to the fragment instantiated.
EDIT: Some more changes since the code wasn't working as intended:
#Override
public void onBackPressed() {
//Here we're gonna remove the last fragment added, and show OptionMenuFragment again
if (!showingFirstFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
transaction.show(firstFragment);
transaction.commit();
showingFirstFragment = true;
} else {
super.onBackPressed();
}
}
And when adding OptionMenuFragment, do this instead:
fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
Related
I have a bottom activity with 3 menus (Fragment). Home , News and Settings. In Setting there is another menus (ListView) . Profil, About and Contact Us.
If you click Profil it will open new activity (Profil.Class) .
My question is how can I open recent tab (Setting), because now if I click back button and back arrow from toolbar it will open My bottom activity with home fragment instead of settings framgent. I trying to send putExtra(); from my SettingFragment but its not working . how can I achieve that?
So here is my MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
Intent intent = getIntent();
Integer tabtoOpen = intent.getIntExtra("Tab",0);
Log.d("TABB", tabtoOpen.toString());
if(tabtoOpen == 0){
fragment = new MainFragment();
}else if(tabtoOpen == 1){
fragment = new NewsFragment();
}else if(tabtoOpen == 2){
fragment = new SettingsFragment();
}
loadFragment(fragment);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
toolbar.setTitle("Home | " +getString(R.string.app_name));
fragment = new MainFragment();
loadFragment(fragment);
return true;
case R.id.navigation_news:
toolbar.setTitle("News | " +getString(R.string.app_name));
fragment = new NewsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_setting:
fragment = new SettingsFragment();
loadFragment(fragment);
toolbar.setTitle("Setting | " +getString(R.string.app_name));
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
and here is my profil
public void onBackPressed() {
Intent i = new Intent(this, Activity_main.class);
i.putExtra("Tab", 2);
this.startActivity(i);
}
And you can set whichever navigation item you'd like to be selected using setSelectedItemId().
else if(tabtoOpen == 2){
navigation.setSelectedItem(R.id.navigation_setting);
}
Basically, I want to get data from Sqlite from two different table (or column) based on which Fragment is visible. I have already find a solution (tricky solution), and I want to know if there are other best way to reach the same result.I've founded a lot of tutorial only on a single Fragment. Below what I've done:
First of all, in my MainActivity I have:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Hai cliccato la barra",Toast.LENGTH_SHORT).show();
fragment = new HomeFragment();
if (fragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area,fragment);
ft.commit();
}
}
});
and from navigationView I can choose which fragment I want to see:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
}
if (fragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.screen_area,fragment);
ft.commit();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id= item.getItemId();
switch(id){
case R.id.carburante:
fragment = new CarburanteFragment();
break;
case R.id.giorni:
fragment = new GiorniFragment();
break;
...after that on my CarburanteFragment I pass the fragment to DbAdapter...for example in "Save":
private void save(String name)
{
DBAdapter db=new DBAdapter(getActivity(),((MainActivity) getActivity()).fragment= this);
db.openDB();
boolean saved=db.add(name);
if(saved)
{
nameEditText.setText("");
this.getSpacecrafts();
}else {
Toast.makeText(getContext(),"Unable To Save",Toast.LENGTH_SHORT).show();
}
}
...finally in DBAdapter class I can get the fragment that I want to populate ListView....for example changing the Constants variable and so on....in the code below I tested only if it works:
public DBAdapter(Context c,Fragment fr) {
this.c = c;
helper = new DBHelper(c);
Fragment currentFragment =fr;
if(currentFragment.getTag()=="carburante")
Toast.makeText(c, currentFragment.toString(), Toast.LENGTH_LONG).show();
}
What you can do is you can pass a flag while replacing the fragment, which can be later used to identify which data you want to load.
For fragment1
Fragment1 frag = new Fragment1();
Bundle bundle = new Bundle ();
bundle.put("MY_FLAG", 1);
frag.setArgument(bundle);
For fragment2
Fragment2 frag = new Fragment2();
Bundle bundle = new Bundle ();
bundle.put("MY_FLAG", 2);
frag.setArgument(bundle);
Then you can use data in the flag to identify which type of data you want to load.
For the first second I making a Android App where students can rent a room. Now I work on the login en register pages.
I have a problem with the register page. In my app there can two types of users register they are called "Student" and "Verhuurder". In the account fragment there are two buttons for the register pages. I can't get it working to the two pages..
I had so much trouble with activity and fragments...
Can anyone help me?
My code :
Account Fragment
public class AccountFragment extends Fragment implements View.OnClickListener{
public AccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (MainActivity.loginId == "")
{
return inflater.inflate(R.layout.fragment_account, container, false);
}
else
{
return inflater.inflate(R.layout.inlog_account, container, false);
}
}
// BUTTON
Button btnStudent = (Button) view.findViewById(R.id.btnRegisterStudent);
btnStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStudent:
//what to put here
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, new AccountFragmentStudent());
ft.commit();
break;
}
}
});
}
XML Account fragment
<Button
android:id="#+id/btnRegisterStudent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:text="Student op zoek naar een kamer"
android:background="#color/colorPrimary"
android:onClick="StudentRegister"/>
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Callback<LoginResults> {
private EditText emailInput;
private EditText passwordInput;
private HomeFragment fragment;
public static String loginId = "";
public static String loginSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void Login(View v) {
emailInput = (EditText) findViewById(R.id.email);
passwordInput = (EditText) findViewById(R.id.password);
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
doLogin(email, password);
}
public void onResponse(Response<LoginResults> response) {
if (response.isSuccess() && response.body() != null) {
loginId = response.body().clientId;
loginSecret = response.body().clientSecret;
fragment.setLoginToken1(loginId);
fragment.setLoginToken2(loginSecret);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Gelukt")
.setMessage("U bent ingelogd")
.setCancelable(false)
.setPositiveButton("oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create().show();
// Create fragment and give it an argument specifying the article it should show
InlogAccountFragment newFragment = new InlogAccountFragment();
Bundle args = new Bundle();
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
else
new AlertDialog.Builder(MainActivity.this)
.setTitle("Mislukt")
.setMessage("Uw inloggegevens zijn incorrect")
.setCancelable(false)
.setPositiveButton("oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create().show();
{
}
}
public void onFailure(Throwable t) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Er is iets fouts gegaan")
.setMessage("Probeer opnieuw")
.setCancelable(false)
.setPositiveButton("oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create().show();
}
public void doLogin(String email, String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("BLABLA")
.addConverterFactory(GsonConverterFactory.create())
.build();
Login service = retrofit.create(Login.class);
service.loginResults(
email,
password
).enqueue(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_favorieten) {
FavoriteFragment fragment = new FavoriteFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_berichtenbox) {
MessageFragment fragment = new MessageFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_account) {
AccountFragment fragment = new AccountFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_instellingen) {
SettingsFragment fragment = new SettingsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I generally try to keep my fragments light and decoupled, and delegate heavy lifting (particularly interaction with other fragments) to the activity which is using them. You might like to try the following approach:
Try adding a listener interface to your AccountFragment - something like this:
public interface Listener {
void onStudentRegistrationSelected();
void onVerhuurderRegistrationSelected();
}
You'll also need to add:
// Member declaration at the top of the fragment class
private Listener mListener;
#Override public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (Listener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement " +
Listener.class.getSimpleName() + ".");
}
}
This will set the activity which is using the fragment as the listener.
Then, set up the on click handler of the appropriate buttons in AccountFragment to call the appropriate method on the listener. Something like this:
view.findViewById(R.id.btnRegisterStudent).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onStudentRegistrationSelected();
}
}
Back in MainActivity, implement the AccountFragment.Listener interface, override the methods of the listener, and create and commit the appropriate registration fragment in each of the listener method overrides - for example, onStudentRegistrationSelected() would display the AccountFragmentStudent fragment. Also, if you add this to the fragment backstack, then the user will be returned to the AccountFragment if they hit the back button while on the AccountFragmentStudent, which is a nice piece of UX.
Hope that helps!
I have a navigation drawer and when I click on one of the menus, I want the default content to disappear, but it just doesn't happen and when I click on a new menu it's still there.
This is really annoying, I've been trying to find solution the whole day and I'm going crazy now.
Please help me out, if you can. Thanks in advance!
I copy the whole code here. (p.s.: this is the first and last time I'm programming on Android, this is a nightmare...I just must do this now :/)
public class About extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
ImageButton FAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
FAB = (ImageButton) findViewById(R.id.imageButton);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(About.this, SecondActivity.class);
startActivity(i);
//FAB click, call other thing...
}
});
navigationView = (NavigationView) findViewById(R.id.nav_view);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ListViewFragment());
fragmentTransaction.commit();
setNavDrawer();
navigationView.setCheckedItem(R.id.nav_gallery);
}
private void setNavDrawer() {
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_camera:
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction f = getSupportFragmentManager().beginTransaction();
f.replace(R.id.content_frame, fragment);
f.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.nav_gallery:
Toast.makeText(getApplicationContext(), "Whatever", Toast.LENGTH_SHORT).show();
UserFragment fragment2 = new UserFragment();
android.support.v4.app.FragmentTransaction f2 = getSupportFragmentManager().beginTransaction();
f2.replace(R.id.content_frame, fragment2);
f2.commit();
return true;
case R.id.nav_slideshow:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_share:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.addDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.about, 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);
}
}
Use these code on menu click..
Fragment fragment = new ContentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new CurrentFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
an also add these lines in xml
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Try this
Fragment fragment = new Fragment();
fragment.setRetainInstance(true);
fragment = new ContentFragment ();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
When i press back button from my Home_Fragment the control will go to a empty page ,i want to exit my application when i press back button from Home_Fragment,at the same time when i press back button from all other fragment i want to navigate to Home_Fragment. My MainActivity page is below.
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
you can write code for onBackButton to check for count of BackStackEntry. if atleast one fragement is in it, Count will be more than 0.
if count==0 then do finish()
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() == 1) {
//no fragments left
finish();
} else {
super.onBackPressed();
}
}
You can try this, It works:
Create a method in main Activity to call fragment:
public void replaceFragment(Fragment fragmentName){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragmentName);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
And call this method by any fragment by the following lines of code:-
((MainActivity)getActivity).replaceFragment(FragmentName.class)