I have an activity and in that i have a textView,Framelayout(having fragments) and a button. while clicking on the button , i am changing the fragments in framelayout and text in textView (according to fragments). On pressing the back button of my phone i am somehow able to get previous fragment with onBackpressed function but not able to get the previous value on the textView. how to do it.
public class Quetionare extends AppCompatActivity {
Toolbar toolbar;
TextView tv;
Fragment fr;
Button next;
intro into;
SelectCar selectCar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quetionare);
initToolbar();
next=(Button)findViewById(R.id.button2);
tv = (TextView)findViewById(R.id.textView5);
fr = new intro();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();
}
private void initToolbar()
{
toolbar = (Toolbar)findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
}
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
public void selectFrag(View view)
{
if(view==findViewById(R.id.button2))
{
fr = new SelectCar();
next.setVisibility(View.GONE);
tv.setText("Select Your car model and Plan");
}
else
{
fr = new Checkbox();
tv.setText("Make Your Plan");
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onBackPressed()
{
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
if (fr == into)
{
next.setVisibility(View.VISIBLE);
}
else
{
next.setVisibility(View.GONE);
}
}
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_quetionare, 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);
}
}
You will have to save the value in the TextView when transitioning to your second fragment to a field, and then call setText using that value when you are navigating back.
we need to use findfragmentbyid method. By using this i have achieved desired functionality. thanks
Related
i am using a Drawer Navigation activity to handle fragments , and i have an options menu to change Locale like this :
public class DrawerNavigationActivity extends AppCompatActivity implements NavigationView
.OnNavigationItemSelectedListener, AgendaMainFragment.OnFragmentInteractionListener,
MediaMainFragment.OnFragmentInteractionListener, VideosFragment
.OnFragmentInteractionListener, PhotosFragment.OnFragmentInteractionListener,
ThemesMainFragment.OnFragmentInteractionListener, AdresseMainFragment
.OnFragmentInteractionListener, InfoMainFragment.OnFragmentInteractionListener,
NewsMainFragment.OnFragmentInteractionListener, BlockMainFragment
.OnFragmentInteractionListener, DemosMainFragment.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setTitle(R.string.app_name);
//########################################################### set initial fragment
Bundle b = getIntent().getExtras();
Fragment fragment = null;
if(b.getInt("link") == 1) {
fragment = new AgendaMainFragment();
}else if(b.getInt("link") == 2){
fragment = new MediaMainFragment();
}else if(b.getInt("link") == 3){
fragment = new ThemesMainFragment();
}else if(b.getInt("link") == 4){
fragment = new AdresseMainFragment();
}else if(b.getInt("link") == 5){
fragment = new InfoMainFragment();
}else if(b.getInt("link") == 6){
fragment = new NewsMainFragment();
}else if(b.getInt("link") == 7){
fragment = new BlockMainFragment();
}else if(b.getInt("link") == 8){
fragment = new DemosMainFragment();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container, fragment);
ft.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.addDrawerListener(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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawer_navigation, 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();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.fr:
LocaleHelper.setLocale(getBaseContext(), "fr");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.ar:
LocaleHelper.setLocale(getBaseContext(), "ar");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.en:
LocaleHelper.setLocale(getBaseContext(), "en");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.es:
LocaleHelper.setLocale(getBaseContext(), "es");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = DrawerNavigationActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
super.onBackPressed();
return true;
} else if(id == R.id.nav_agenda) {
fragment = new AgendaMainFragment();
} else if (id == R.id.nav_gallery) {
fragment = new MediaMainFragment();
} else if (id == R.id.nav_themes) {
fragment = new ThemesMainFragment();
} else if (id == R.id.nav_adresse) {
fragment = new AdresseMainFragment();
}else if (id == R.id.nav_info) {
fragment = new InfoMainFragment();
}else if (id == R.id.nav_news) {
fragment = new NewsMainFragment();
}else if (id == R.id.nav_blocs) {
fragment = new BlockMainFragment();
}else if (id == R.id.nav_demo_animation) {
fragment = new DemosMainFragment();
}else{
return true;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container,fragment);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onAgendaFragmentInteraction(Uri uri) {
}
#Override
public void onMediaFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentPhotoInteraction(Uri uri) {
}
for my fragments i change the bar action title like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news_main, container, false);
LocaleHelper.updateGlobalConfig(getContext());
getActivity().setTitle(getResources().getString(R.string.fgmt_titre_news));
return view;
}
it's working fin except for an RTL language , when i choose and RTL locale it change the title and the content but keeps the layout orientation LTR , so if i close the application and reopen again it changes the oriontation to RTL but keeps it even for LTR fragments:
by orientation i mean the action bar and the drawer navigation.
Fragment with local Fr :
Change Local to AR (RTL)
close the App and reopen it and navigate to RTL fragment
navigate to another LTR fragment (it keeps RTL Layout Orientation)
what am i doing wrong and what is the best and clean way to achieve it ?
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");
I WAS WORKING BY THE EXAMPLE YOU JUST GAVE ME AS DUPLICATE, READ THE ENTIRE POST, TY
I'm making a simple app with sliding menu by using the template provided by android studio. And I have to use fragments to switch between items of the sliding menu.
What I wanna do? (check app design at the bottom)
When I click on button pass data it should set the text in the Fragment B to the text that I entered in a Fragment A but without going directly to the Fragment B. So when I press the button pass data then I wanna go to the sliding menu and select item that containts fragment B and then I wanna see the text from Fragment A. Thanks in advance.
public class MainActivity extends AppCompatActivity implements FragmentA.DataPassListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
displayFragmentA();
} else if (id == R.id.nav_gallery) {
displayFragmentB();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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);
}
#Override
public void passData(String data) {
FragmentB fragmentB = new FragmentB();
Bundle args = new Bundle();
args.putString("data", data);
fragmentB.setArguments(args);
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentB).commit();
//it works with the commented part but I dont wanna go directly to the fragment when I press pass data button
}
public void displayFragmentA() {
FragmentA frag = new FragmentA();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
public void displayFragmentB() {
FragmentB frag = new FragmentB();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
}
Fragment A code:
public class FragmentA extends Fragment {
DataPassListener mCallback;
public interface DataPassListener {
public void passData(String data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Make sure that container activity implement the callback interface
try {
mCallback = (DataPassListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
final EditText input = (EditText) view.findViewById(R.id.etInputID);
Button passDataButton = (Button) view.findViewById(R.id.bPassDataID);
passDataButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.passData(input.getText().toString());
}
});
return view;
}
}
Fragment B code:
public class FragmentB extends Fragment {
TextView showReceivedData;
public FragmentB() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_b, container, false);
showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
Bundle args = getArguments();
if (args != null) {
showReceivedData.setText(args.getString("data"));
} else {
Toast.makeText(getActivity(), "didnt get the bundle from mainactivity", Toast.LENGTH_LONG).show();
}
return view;
}
}
Design of the app:
If these two fragments use same activity,
to set value to fragment :
getActivity().getIntent().putExtra("key", "value");
To get value from fragment :
getActivity().getIntent().getExtras().getString("key");
I have a Mainactivity which contains a Layout which is parent of 4 sub layout. on clicking on sub layout i am going to a new fragment replacing main layout. But i cant go back to MainActivity after pressing Back button
MainActivity.java
public class MainActivity extends AppCompatActivity {
RelativeLayout aboutUs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aboutUs = (RelativeLayout) findViewById(R.id.aboutUs);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//click methods goes here
public void clickAboutUs(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
fragmentTransaction.replace(R.id.fragment_container,fragmentAboutUs);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
FragmentAboutUs.java
public class FragmentAboutUs extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_us, container,false);
return view;
}
}
How to go back to main page again after pressing back button from fragment.
Try Like this
public boolean popFragment() {
boolean isPop = false;
Fragment currentFragment = getSupportFragmentManager()
.findFragmentById(R.id.flContent);
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStackImmediate();
}
return isPop;
}
#Override
public void onBackPressed() {
if (!popFragment()) {
finish();
}
}
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
add above method is in your parent Activity
And Use like
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
replaceFragment(fragmentAboutUs , true);
If you have one Activity and four fragments then set onBackPressed() as below in your MainActivity.
#Override
public void onBackPressed()
{
super.onBackPressed();
finish();
}
And in fragments:
#Override
public void onResume() {
super.onResume();
new PlayListFragment();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
return false;
}
});
}
You can Override the onBackPressed of MainActivity
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Here is how it can be done in Xamarin:
Load fragment (I wrote helper method for that, but it's not necessary):
public void LoadFragment(Activity activity, Fragment fragment)
{
var backStateName = fragment.GetType().Name;
var fm = activity.FragmentManager;
var ft = fm.BeginTransaction();
ft.Replace(Resource.Id.mainContainer, fragment);
ft.AddToBackStack(backStateName);
ft.Commit();
}
Back button (in MainActivity):
public override void OnBackPressed()
{
if (isNavDrawerOpen()) drawerLayout.CloseDrawers();
else
{
var backStackEntryCount = FragmentManager.BackStackEntryCount;
if (backStackEntryCount == 1) Finish();
else if (backStackEntryCount > 1) FragmentManager.PopBackStack();
else base.OnBackPressed();
}
}
isNavDrawerOpen method:
bool isNavDrawerOpen()
{
return drawerLayout != null && drawerLayout.IsDrawerOpen(Android.Support.V4.View.GravityCompat.Start);
}
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)