In my app I am using a navigation drawer to go different fragment. But when I clicked back button it exit from app. I want when back button clicked in any fragment it navigate to home fragment.
drawer_activity.java to navigate different fragment
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
toolbar.setTitle("HOME");
fragment = new HomeFragment();
} else if (id == R.id.wishlist) {
toolbar.setTitle("YOUR WISHLIST");
} else if (id == R.id.order) {
toolbar.setTitle("YOUR ORDER HISTORY");
} else if (id == R.id.cart) {
toolbar.setTitle("YOUR CART");
} else if (id == R.id.nav_share) {
toolbar.setTitle("HOME");
} else if (id == R.id.account) {
toolbar.setTitle("YOUR ACCOUNT");
} else if (id == R.id.logout) {
finish();
SharedPrefManager.getInstance(getApplicationContext()).logout();
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
homefragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_home, container,false);
//getting the recyclerview from xml
recyclerView = (RecyclerView) rootView.findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
categoryList = new ArrayList<>();
loadCategory();
customCategoryList = new CustomCategoryList(getActivity(),categoryList);
recyclerView.setAdapter(customCategoryList);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
int id = categoryList.get(position).getCategoryid();
String category = categoryList.get(position).getCategoryname();
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
ID.setCategoryid(id);
ID.setCategory(category);
Log.e("categoryid",ID.getCategoryid()+"");
Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content, fragment);
ft.commit();
}
#Override
public void onLongClick(View view, int position) {
}
}));
return rootView;
}
In this fragment when one item click from recycler view it navigate to another fragment. From that fragment when I click back button of my phone it exit from app. I want when back button clicked It goes home fragment always and only back button click from home fragment app exit.
productlistFragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
category = (TextView) rootView.findViewById(R.id.category);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
category.setText(ID.getCategory());
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productid = productList.get(position).getProductid();
final GlobalVariable Id = (GlobalVariable)getActivity().getApplication();
Id.setProductid(productid);
Intent intent = new Intent(getActivity(), ProductView.class);
startActivity(intent);
}
});
return rootView;
}
content.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".DrawerActivity"
tools:showIn="#layout/app_bar_drawer">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Ok!! Just copy this code and paste you will get what yout want.ft.addToBackStack(null); is the key here.
Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content, fragment);
ft.commit();
Related
Working on an app that included 3 fragments. I want to retain data in the FragmentA when the user decides to switch back to FragmentA from FragmentB or FragmentC via BottomNavigationView.
My code works great with changing screen orientation, but for some reason it wont retain data on fragment change.
For testing, I've used only one EditText that should retain data from string.
MainActivity
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
Fragment Frag = new Fragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this); // mOnNavigationItemSelectedListener
if (savedInstanceState != null)
{
Frag = getSupportFragmentManager().getFragment(savedInstanceState, "Frag");
}
else
loadFragment(new FragmentA());
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
int i = menuItem.getItemId();
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment)
{
if (fragment != null)
{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
Frag = fragment;
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Frag", Frag);
}
}
FragmentA
public class FragmentA extends Fragment {
EditText editText;
String string;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
string = savedInstanceState.getString("Text", "");
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.fragmentA, container, false);
editText = view.findViewById(R.id.centerText);
editText.setText(string);
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
string = editText.getText().toString();
outState.putString("Text", string);
}
}
I want that editText retains data when user switches back to FragmentA from FragmentB or FragmentC.
I've been struggling with this problem for some time now, trying different methods with no luck.
Either you can keep the references to your fragments, instead of creating new ones every time like you do here:
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
You could also use a ViewPager which allows you not only to swipe in-between the screens, but to set viewPager.setOffscreenPageLimit(i); which means that fragments will not be recreated unless they're too far off screen.
Here is your mistake
if (i == R.id.fragmentA) {
fragment = new FragmentA();
} else if (i == R.id.fragmentB) {
fragment = new FragmentB();
} else if (i == R.id.fragmentC) {
fragment = new FragmentC();
}
On click you create new fragment instance
Thank you for your replies.
This is what I changed. It is now working although I'm not sure if that's the elegant way to solve this problem. Data now retains in EditText while navigating back to FragmentA.
MainActivity
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
Fragment Frag = new Fragment();
Fragment FragmentA;
Fragment FragmentB;
Fragment FragmentC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this); // mOnNavigationItemSelectedListener
FragmentA = new FragmentA();
FragmentB = new FragmentB();
FragmentC = new FragmentC();
if (savedInstanceState != null)
{
Frag = getSupportFragmentManager().getFragment(savedInstanceState, "Frag");
}
else
loadFragment(FragmentA);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
int i = menuItem.getItemId();
if (i == R.id.fragmentA) {
fragment = FragmentA;
} else if (i == R.id.fragmentB) {
fragment = FragmentB;
} else if (i == R.id.fragmentC) {
fragment = FragmentC;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment)
{
if (fragment != null)
{
getSupportFragmentManager().beginTransaction().hide(FragmentA).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
getSupportFragmentManager().beginTransaction().show(fragment).commit();
Frag = fragment;
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "Frag", Frag);
}
}
I've been struggling for few days on this issue. My project is having 4 fragments which share the same floating button. I have managed to reference the fragments in order to allow the floating button to access each, however although I'm shifting between each fragment, it showing the position of the first one only. here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNavigationViewListener();
//set the drawer layout and navigation view
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
//set item selected persist highlight
menuItem.setChecked(true);
//close drawer
mDrawerLayout.closeDrawers();
//set action as per the item selected
return true;
}
});
//create an adapter that knows where each fragment is
final LocationFragmentAdapter adapter = new LocationFragmentAdapter(this, getSupportFragmentManager());
mViewPager = findViewById(R.id.viewPager);
mViewPager.setAdapter(adapter);
adapter.getItem(position);
//set the function for the floating button to add a new item
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "the current fragment " + adapter.getPageTitle(position));
if(position == 0) {
Intent intent = new Intent(MainActivity.this, EditorActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(MainActivity.this, RecipeEditor.class);
startActivity(intent);
}
}
});
}
this is my fragmentAdapter
public class LocationFragmentAdapter extends FragmentPagerAdapter {
final int count = 4;
private int [] tabTitle = {R.string.inventory_platform, R.string.product_platform, R.string.customer_platform, R.string.order_platform};
private Context mContext;
public LocationFragmentAdapter(Context context, FragmentManager fm){
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return new InventoryFragment();
}else if(position == 1) {
return new RecipeFragment();
}else if(position == 2) {
return new CustomerFragment();
}else {
return new OrderFragment();
}
}
thats my InventoryFragment
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(STOCK_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new PlatformCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opend the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(StoreEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
getLoaderManager().initLoader(STOCK_LOADER, null, this);
return rootView;
}
and my RecipeFragment
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(RECIPE_lOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new RecipeCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opened the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(RecipeEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
return rootView;
}
I haven't created the last two fragments yet. Please let me know if you can find the error.
The log message is always showing the Inventory Fragment
You will have to update the position every time a page is selected using a pager listener
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
this.position = position
}
});
When we want to change Activity we can use:
Intent i = new Intent(this، ActivityTwo.class);
startActivity(i);
When i use it in some Activity it work correctly
But it dose not work when I use it in navigation drawer project. I think it dose not work beacuse Test class extends Fragment. in AppCompatActivity it work.
public class Test extends Fragment {
public Test() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_test , container, false);
button= (Button) v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent((getActivity(), ActivityTwo.class);
startActivity(i);
}
});
return v;
}
}
In my MainActivity I change code:
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment=null;
if (id == R.id.nav_camera) {
Test contactUsFragment=new Test();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,contactUsFragment).commit();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
ActivityTwoss=new ActivityTwo();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,ss).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
You create a xml container? If so, use a Fragment, not an Activity, for the FragmentManager
In my MainActivity I change code:
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment=null;
if (id == R.id.nav_camera) {
Test contactUsFragment=new Test();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout,contactUsFragment).commit();
} else if (id == R.id.nav_gallery) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_conteiner, new Test(), "Test");
transaction.commit();
} else if (id == R.id.nav_slideshow) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
MainActivity xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="br.com.onuse.finds.Activity.MainActivity"
tools:showIn="#layout/fragment_conteiner"
android:id="#+id/fragment_conteiner">
</FrameLayout>
I think you want to start a new Activity from your Fragment using the following sentence:
Intent i = new Intent((getActivity(), ActivityTwo.class);
startActivity(i);
Well, that won't work. You should start your Activity from your current activity (not from your Fragment). You may use something like this:
Intent i = new Intent((getActivity(), ActivityTwo.class);
getActivity().startActivity(i);
Or you can do that in one line from your Fragment:
getActivity().startActivity(new Intent(getActivity(), ActivityTwo.class));
Let me know if that works for you!
I am having a problem. I have an activity that implements several fragments. Now I need to update a textview of one of the fragments, I have the string in the activity, so I need to pass this string to the fragment and update that textview.
NavigationDrawer.java --> this is the activity
String user = "";
InicialPage inicialpage = new InicialPage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_naviagation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
user = extras.getString("KEY"); // TODO this is the value that i need to pass to the fragment InicialPage
}
Bundle bundle = new Bundle();
bundle.putString("USER", user);
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);
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
//inicialpage.setUsernameTextView(user);
DrawerLayout drawer1 = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer1.closeDrawer(GravityCompat.START);
TextView userNameTextView = (TextView)findViewById(R.id.usernametext);
//userNameTextView.setText(user);
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.InicialPage);
}
#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.naviagation_drawer, 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();
android.support.v4.app.FragmentTransaction fragmenttransaction =
getSupportFragmentManager().beginTransaction();
if (id == R.id.InicialPage) {
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
} else if (id == R.id.HistoryItem) {
fragmenttransaction.replace(R.id.container, new Historic());
fragmenttransaction.commit();
} else if (id == R.id.FriendsItem) {
fragmenttransaction.replace(R.id.container, new Friends());
fragmenttransaction.commit();
} else if (id == R.id.PointsItem) {
fragmenttransaction.replace(R.id.container, new Points());
fragmenttransaction.commit();
} else if (id == R.id.BookBikeItem) {
fragmenttransaction.replace(R.id.container, new BookBike());
fragmenttransaction.commit();
} else if (id == R.id.MessagesItem) {
fragmenttransaction.replace(R.id.container, new Messages());
fragmenttransaction.commit();
}else if(id == R.id.Mapdebug)
{
Intent maps = new Intent(this,MapsActivity.class);
startActivity(maps);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void FrameClicked(View view) {
//send user name to chat
Intent i = new Intent(this, Chat.class);
i.putExtra("USER", user);
startActivity(i);
}
public void addFriend(View view) {
LinearLayout principalLayout= (LinearLayout) findViewById(R.id.idFriendsVertical);
LinearLayout secondaryLauout= new LinearLayout(this);
TextView tx= new TextView(this);
EditText et= (EditText) findViewById(R.id.ADD);
String edittx= String.valueOf(et.getText().toString());
if (edittx.equals("")) {
}else
{
tx.setText(edittx);
tx.setTextSize(22);
tx.setTextColor(Color.BLACK);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.setMargins(0, 20, 0, 10);
secondaryLauout.addView(tx, params);
principalLayout.addView(secondaryLauout);
}
et.setText("");
}
}
InicialPage.java --> this is the fragment
public class InicialPage extends Fragment {
SQLiteDatabase db;
View view;
TextView usernameTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_inicial_page, container, false);
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
return view;
}
If I understand your question correctly, you need to add inicialpage.setArguments(bundle); before your replace and commit in your fragment transaction.
Then, inside your Fragment you call
Bundle bundle = getArguments();
String bundleText = bundle.getString("USER");
to retrieve it.
You were already creating a bundle so I'm assuming that's the data you want to send. You have to attach that bundle to the Fragment before your Fragment Transaction though.
Inside your Activity:
Bundle bundle = new Bundle(); //create the bundle
bundle.putString("USER", user); //attach data to the bundle
inicialpage.setArguments(bundle); //set the bundle on the fragment
//perform fragment transaction
fragmenttransaction.replace(R.id.container, inicialpage);
fragmenttransaction.commit();
Inside your Fragment:
//retrieve the bundle
Bundle bundle = getArguments(); //retrieve the bundle
String bundleText = bundle.getString("USER"); //get the data on the bundle
//find view & set the text
usernameTextView = (TextView) view.findViewById(R.id.usernametext);
usernameTextView.setText(bundleText);
This type of problem can be solved using Localbroadcast Receiver .Write the following code in your fragment. Something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
usernameTextView.setText(message);
Log.d("receiver", "Got message: " + message);
}
};
then pass the user value by adding this following code in your activity when you want to pass
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", user);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
I have an OnClickListener in a fragment activity as shown here:
public class Menu1_Fragment extends Fragment {
Button CreateGroupButton;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
CreateGroupButton = (Button) rootview.findViewById(R.id.create_study_group);
CreateGroupButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Menu1_Fragment.this.getActivity(), CreateGroup.class);
startActivity(intent);
}
});
return rootview;
}
}
Here is my menu1_layout.xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="#+id/create_study_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/CreateGroupBtn"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where you can create and view existing groups"
android:id="#+id/textView"
android:layout_below="#+id/create_study_group"/>
</RelativeLayout>
When the Button is clicked, the "Test" message is displayed but the app closes right after.
Here is the CreateGroup java class:
public class CreateGroup extends Fragment{
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.create_group, container, false);
return rootview;
}
}
and the create_group.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where the form is displayed"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
NavigationActivity:
public class NavigationActivity extends FragmentActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
FragmentManager fragmentManager = getSupportFragmentManager();
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();
Fragment fragment= new Fragment();
switch (position){
case 0:
mTitle = getString(R.string.title_section1);
fragment = new Menu1_Fragment();
break;
case 1:
mTitle = getString(R.string.title_section2);
fragment = new Menu2_Fragment();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
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;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
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.navigation, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//if the log out button is selected, log out of Parse and go back to log in page
if (id == R.id.action_logout) {
ParseUser.logOut();
Intent intent = new Intent(NavigationActivity.this,LoginSignupActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Logged out", Toast.LENGTH_LONG).show();
finish();
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
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_navigation, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((NavigationActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I'm having trouble figuring out why the CreateGroup class/layout file aren't being displayed as a new page.
The CreateGroup class is a fragment , the intent should be using an activity if startActivity is being used
CreateGroup is a fragment, so you should change fragments and not start an activity:
CreateGroupButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
// Create new fragment and transaction
Fragment createGroupFragment = new CreateGroup();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, createGroupFragment)
.commit();
}
});