How to send data from main activity to fragment - android

public class MyActivity extends Activity implements ButtonFragement.OnFragmentInteractionListener, TextFragment.OnFragmentInteractionListener,Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ButtonFragement btnfrg=new ButtonFragement();
TextFragment txtfrg= new TextFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.my_activity,btnfrg,"Fragment");
ft.add(R.id.my_activity,txtfrg,"Second Fragment");
ft.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.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void respond(String data) {
FragmentManager fm=getFragmentManager();
TextFragment f1= (TextFragment) fm.findFragmentById(R.id.textfrg);
f1.changeText(data);
}
}
This is my main_Activity code, here i am trying to send a data over the fragment but it gives me error at f1.changeText(data).Basic structure of my project is , on main Activity , i created two fragment. One with button and another with text. I want to show how many times the button was clicked on second fragment using a communicator interface. Here in "data" counter shows a how many times button was clicked but i am not able to transfer it over second fragment.
Complete Code for the Program---
public interface Communicator {
public void respond(String data);
}
In TextFragment class i added this method----
public void changeText(String data)
{
txt.setText(data);
}
In ButtonFragment class i added and modified following method
public class ButtonFragement extends Fragment implements View.OnClickListener{
int counter=0;
private OnFragmentInteractionListener mListener;
Button btn;
Communicator comm;
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
comm= (Communicator) getActivity();
btn= (Button) getActivity().findViewById(R.id.button);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
counter++;
// comm.respond("The button was clicked "+counter+" times");
comm.respond("hi");
}
Here, i just added which i added in my program. My program get crash at...MainActiviy f1.changeText(data);
But why i am not getting it.Can anyone Help me fixed this bug?

Bundle bundle = new Bundle();
bundle.putString("key", value);
// set Fragmentclass Arguments
YourFragment ff= new YourFragment ();
ff.setArguments(bundle);
transaction.add(R.id.my_activity, ff);

Using Bundle
From Activity:
Bundle bundle = new Bundle();
bundle.putString("message", "Hello!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String myValue = this.getArguments().getString("message");
...
...
}

You have no fragment with id R.id.textfrg.
You are for some reason adding two fragments with id R.id.my_activity. One with tag "Fragment" and another with tag "Second Fragment".
So you are getting error.
Your idea is rigth.
This may be helpfull
TextFragment f1= (TextFragment) fm.findFragmentByTag("Second Fragment");

DO this way:
On Activity Side.
Fragment fragment = new GridTemplate();
Bundle bundle = new Bundle();
bundle.putInt("index",your value);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
here R.id.frame_container is a frame Layout or Relative Layout In which you have to add the fragment.
On Fragment Side.
int index = getArguments().getInt("index");
hope this wil solve your problem. Thanks

Related

How to return to Previous Fragment by clicking back(Not Hardware back button)?

I have only 1 activity with 2 Fragments within it. When start the activity, Fragment A will launch. After user key in sth and click the button will direct to Fragment B. So what I want to do is that by adding a "Back Arrow" sth like this <- at the top left hand corner.
Does it has to do with FragmentManager.popBackStack()? Please advice ! Thx
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
first first=new first();
transaction.add(R.id.top,first);
transaction.commit();
}
}
first.java
public class first extends Fragment implements View.OnClickListener{
Button get_button;
EditText get_input_name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,container,false);
get_input_name=(EditText)rootView.findViewById(R.id.input_name);
get_button=(Button)rootView.findViewById(R.id.submit);
get_button.setOnClickListener(this);
return rootView;
}
public void onClick(View v){
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two();
Bundle bundle = new Bundle();
bundle.putString("input_name_value",get_input_name.getText().toString());
Two.setArguments(bundle);
transaction.replace(R.id.top,Two);
transaction.commit();
}
}
two.java
public class two extends Fragment implements View.OnClickListener {
TextView get_display_input;
ImageView get_back_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
get_display_input=(TextView)getActivity().findViewById(R.id.display_input);
get_back_button=(ImageView) getActivity().findViewById(R.id.back_button);
Bundle bundle = getArguments();
String get_name = bundle.getString("input_name_value");
//int store_get_input=Integer.parseInt(get_name);
get_display_input.setText("You have entered "+get_name);
}
public void onClick(View v){
// WHAT TO DO HERE IN ORDER TO RETURN TO PREVIOUS Fragment when clicking the button?
}
}
To be more precise, please refer to the screenshot.
You can do it by using the popBackStack() method of FragmentManager, put this inside the onClickListener of your back button :
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
If you're using the default back button of the toolbar i.e, the home button, then you can do it by placing this code in the onOptionsItemSelected() method of your Activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
return true;
}
return super.onOptionsItemSelected(item);
}
or, if you want the same behaviour on hardware back button press then override the onBackPressed() method in your Activity class like this:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Check out the training docs here -- they should give you a good start.
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
You just need this one single line of code!
getFragmentManager().popBackStackImmediate();
Yes, it has to do with FragmentManager.popBackStack();
Take a look here, there are plenty of methods:
https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack
For me, getFragmentManager().popBackStackImmediate(); made exactly that.
In your Activity to handle hardware back button:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
So for button click method:
getFragmentManager().popBackStack();
Well I know I am too late to answer this but you can just call getActivity.onBackpress(); method on back click of that back icon.

Navigation Drawer AsyncTask

I would like to expose my problem and I want to know how I could solve it.
In my application I'm using an activity, making a simple login, launching a asyncTask. At the end of this task, the user is redirected to another activity, which is the home activity of application. The latter has the task of managing a navigation drawer and its fragments. The contents of each fragment must be populated with data retrieved from a server and the navigation drawer set the default fragment F1, which is displayed after the user has logged on.
Now the problem is:
How can I recover the data necessary to populate the listView contained in fragment1?
I know how to implement an adapter for the listView, but I don't understand how to communicate the home activity with the fragment F1. My intention would be to retrieve a circular dialog (content in F1) and run it as long as the data required for the adapter have not been recovered.
Here some code:
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Login().execute();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Login");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (progessDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected Void doInBackground(String... params) {
// code to retrieve data.
}
}
}
public class HomeActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer fragmentDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
fragmentDrawer = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
fragmentDrawer.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fragmentDrawer.setDrawerListener(this);
// Here the problem!!!
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayView(int position) {
switch (position) {
case 0:
Fragment fragmentOne = new FragmentOne();
move(matchFragment);
break;
case 1:
Fragment fragmentTwo = new FragmentTwo();
move(teamFragment);
break;
case 2:
Fragment fragmentThree = new FragmentThree();
move(myTeamFragment);
break;
case 3:
//other fragment....
default:
break;
}
}
public void move (Fragment fragment) {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment, fragment.getClass().getSimpleName());
fragmentTransaction.commit();
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
}
public class FragmentOne extends Fragment {
private ListView listView;
private ArrayList<Info> infos;
private InfoAdapter infoAdapter;
public FragmentOne() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_match, container, false);
listView = (ListView) rootView.findViewById(R.id.match_list_view);
return rootView;
}
}
Now, where do I implement the AsyncTask to retrieve data for adapter? In fragment or the Activity?
If it were the Activity, how can I recover the elements of view of fragment?
Thanks in advance and sorry for bad english.
for your first quesiton:
I don't understand how to communicate the home activity with the
fragment F1
You can pass information from HomeActivity to the Fragment through parameters passed to the Fragment's constructors. So instead of Fragment fragmentOne = new FragmentOne();, you can call Fragment fragmentOne = new FragmentOne(A a); where a is data you want to pass to the fragment. Of course, you need to add in the constructor with parameters to the Fragment class.
For the 2nd point:
Now, where do I implement the AsyncTask to retrieve data for adapter?
In fragment or the Activity? If it were the Activity, how can I
recover the elements of view of fragment?
You can put AsynchTask call inside onCreate() to load data for the listView...etc. Another option which I prefer is to use Loaders. Please see this documentation on Loaders here http://developer.android.com/guide/components/loaders.html. It also has an example.
For explanation and sample, you can follow these 4-part tutorials:
http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html.

Click Hardware back button in fragment to move back to GridActivity

I have to move Detailfragment to GridActivity.Workflow for activity
is GridActivity ->HomeActivity->DetailFragment.
In GridActvity I am using an image button.On Click the image button I
had set the position to move HomeActivity onArticlelistener.
With this listener I can move to fragment using position.
GridActivity1.java:
int position;
........
........
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_tour:
Intent i1=new Intent(GridActivity1.this,MainActivity.class);
i1.putExtra("tour",2);
i1.putExtra("position", position);
startActivity(i1);
break;
}
}
MainActivity.java:
public class MainActivity extends ActionBarActivity implements OnTabChangeListener,ArticleSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_main_tab_fragment_layout);
posGrid= getIntent().getExtras().getInt("position");
switch(posGrid){
case 0:
int posTour = getIntent().getIntExtra("tour", 0);
articleSelected(posTour, "Tour Guide");
break;
}
}
#Override
public void onArticleSelected(int position, String content)
{
articleSelected(position, content);
}
public void articleSelected(int position, String content)
{
if(position==2)
{
action_bar_hometext.setText(content);
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
DetailFragment newFragment = new DetailFragment();
ft.replace(R.id.realtabcontent, newFragment);
ft.addToBackStack(null);
ft.commit();
}
}
DetailFragment.java:
public class TourGuideFirstFragment extends BaseFragment implements
OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_tour_guide, container,
false);
return view;
}
}
I don't need action bar back button.Because I am using navigation
drawer in fragments.
My issue is,when I click the hardware back button in DetailFragment I
need to move directly to GridActivity.Now it is moving to HomeActivity then it back to GridActivity.
You are adding a FragmentTransaction to the backstack, so in order to get rid of this you just have to remove the line from MainActivity
ft.addToBackStack(null);
After that it should work as you want it to work

How to remove the fragments so it wont appear in the next activity?

So i've just started doing some android programing, and I'm already stuck! My problem is; I want want my fragment, from MainActivity, to NOT be a part of my new Activity. I want the activity to be all blank, the fragment from MainActivity should be gone, buuut it's not.
The content from the "fragmentz" xml document, which is "linked" in the Fragment Class. Should NOT appear in the second Activity... Where in the SecondActivity have I associated it with the Fragment Class? This is getting frustrating :D
So here is my MainActivity code:
public class MainActivity extends ActionBarActivity {
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
manager= getSupportFragmentManager();
ArticleFragment frag = new ArticleFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
transaction.add(R.id.fragmentet,frag,"tagg");
transaction.commit();
// here the Fragment should be added to my MainActiviy
}
public void WalkForward(View view)
{
ArticleFragment frag = (ArticleFragment) manager.findFragmentByTag("tagg");
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(frag);
transaction.commit();
// Here, the fragment should disappear before the new activity start
Intent intenten = new Intent(this, SecondActivity.class);
startActivity(intenten);
// Start new activity
finish();
// I've tried this finish method, and also onDestroy and so on... But that work either. I thought the Fragments should
// disappear with its activity?
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
My Fragment Class:
public class ArticleFragment extends Fragment {
public void onAttach(Activity activity)
{
Log.d("Fraggment", "onAttach");
super.onAttach(activity);
// #17 Android FragmentTransaction Part 2: Android Application Development Development [HD 1080p]
}
public void onCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onCreate");
super.onCreate(saveInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentz, container, false);
}
public void onActivityCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onActivityCreated");
super.onActivityCreated(saveInstanceState);
}
public void onPause()
{
super.onPause();
Log.d("Fraggment", "onPause");
}
public void onStop()
{
super.onStop();
Log.d("Fraggment", "onStop");
}
public void onDestroyView()
{
super.onDestroyView();
Log.d("Fraggment", "onDestroyView");
}
public void onDestroy()
{
super.onDestroy();
Log.d("Fraggment", "onDestroy");
}
public void onDetach()
{
super.onDetach();
Log.d("Fraggment", "onDetach");
}
And my Second Activity Class:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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.second, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second,
container, false);
return rootView;
}
}
}
I hope you understand what I mean :P Is there anything I can do? Thanks in advance!
Remove this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
from your Second Activity. And why are you extending MainActivity? Some Reason?

Android onOptionsItemSelected is not functioning

I'm working on go-back function with my fragments. I use the action bar as return button but the function onOptionsItemSelected does not work (the function may be even not called)
This code is in my FragmentActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
getActionBar().setHomeButtonEnabled(false);//disable the back button
this.getFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bottom_tab);
FragmentTabHost tabHost = (FragmentTabHost)findViewById(R.id.bottom_tab_host);
tabHost.setup(this, getSupportFragmentManager(), R.id.bottom_tab_content);
//tabHost.addTab(tabHost.newTabSpec("explore").setIndicator("explore"), ListTabWidget.class, null);
tabHost.addTab(tabHost.newTabSpec("browse").setIndicator("browse"), SearchList.class, null);
}
And this code is in my Fragment(A):
public class SearchList extends Fragment implements SearchView.OnQueryTextListener{
FragmentActivity searchActivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
searchActivity = (FragmentActivity) this.getActivity();
View searchView = inflater.inflate(R.layout.search_list, container, false);
SearchView searchBar = (SearchView)searchView.findViewById(R.id.browse_search);
searchBar.setIconifiedByDefault(false); //Showing text field in search
searchBar.setSubmitButtonEnabled(true);
searchBar.setOnQueryTextListener(this);
return searchView;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
/*Intent intent = new Intent(Intent.ACTION_SEARCH, null, searchActivity, BrowseGrid.class);
intent.putExtra(SearchManager.QUERY, query);
startActivity(intent);*/
Bundle args = new Bundle();
args.putString("search_query", query);
BrowseGrid browseFragment = new BrowseGrid();
browseFragment.setArguments(args);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.bottom_tab_content, browseFragment);
transaction.addToBackStack(null);
transaction.commit();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
}
and Fragment(B):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.grid_list, container, false);
gridView = (GridView)view.findViewById(R.id.gridView);
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
return view;
}
The aim is very simple. Pressing the back button, Fragment goes back from B to A.
Am I missing something?
As I found that the stack actually has nothing to pop(I wanna know why...), I choose an alternative to do so.
I don't know whether it is the best solution but it seems work.
replace
getFragmentManager().popBackStack();
to
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount()>0){
//Log.d("Bottom Tab", "popping backstack");
fm.popBackStack();
} else {
//Log.d("Bottom Tab", "nothing can pop");
super.onBackPressed();
}
Even the stack has nothing, it will override the onBackPressed() to go back.
How about try using the SupportFragmentManager on both Activity and Fragment(A)
currently the Fragment (A) is using
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
While in you activity onOptionsItemSelected is using
this.getFragmentManager().popBackStack();
change it to:
getSupportFragmentManager().popBackStack();
Change this line , as you are handling the FragmentTransaction from Fragment class not Activity itself. You need to get getParentFragment() first.
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
To
FragmentTransaction transaction = getActivity().getParentFragment().getFragmentManager().beginTransaction();
transaction.replace(R.id.bottom_tab_content, browseFragment);

Categories

Resources