I want to refresh the content of the fragment when a user clicks the refresher icon which is in menu action bar.
My application has three fragments on one activity with view pager; I tried to refresh all of them by calling them in onOptionsItemSelected() and I performed transactions to them, the application crashes when a user clicks refresh menu.
I read this question, it is likely similar to mine, but I couldn't find an appropriate answer to settle my problem: android: menu item click event from fragment I read this article too: but nothing helped me: https://developer.android.com/guide/topics/ui/menus maybe I am not doing it in a right way.
My code of refreshing all three fragments in the activity are here below:
#Override
public boolean onOptionsItemSelected(MenuItem item){
Fragment sentMsg=getSupportFragmentManager().findFragmentByTag("fragmentSentMsg");
Fragment receivedMsg=getSupportFragmentManager().findFragmentByTag("fragmentReceivedMsg");
Fragment allMsg=getSupportFragmentManager().findFragmentByTag("fragmentAllMsg");
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
switch (item.getItemId()){
case R.id.refresher_id:
fragmentTransaction.detach(sentMsg).attach(sentMsg).commit();
fragmentTransaction.detach(receivedMsg).attach(receivedMsg).commit();
fragmentTransaction.detach(allMsg).attach(allMsg).commit();
break;
}
return super.onOptionsItemSelected(item);
}
These are the code of a one fragment:
public class Page2_sent_msg extends Fragment {
//default constructor
public Page2_sent_msg(){}
#SuppressLint("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
final View Page2_sent_msg=inflater.inflate(R.layout.page2_sent_msg,container,false);
ListView sentMsgListView=(ListView)Page2_sent_msg.findViewById(R.id.sentMsgListview);
ArrayList<String> sentMsgArrayList=new ArrayList<String>();
SQLite_database_helper_class myDb=new SQLite_database_helper_class(getContext());
Cursor result=myDb.getting_sms_from_db();
if (result.moveToFirst()){
do {
if (!result.getString(3).equals("Sent message")){
continue;
}else{
sentMsgArrayList.add("SMS No : "+result.getString(0)+"\n"
+"Address : "+result.getString(1)+"\n"
+"Date : "+result.getString(2)+"\n"
+"Type : "+result.getString(3)+"\n"
+"Content : "+"\n________\n\n"+result.getString(4)+"\n");
}
}while (result.moveToNext());
}
ArrayAdapter<String>sentMsgAdapter=new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,sentMsgArrayList);
sentMsgListView.setAdapter(sentMsgAdapter);
sentMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//this is what will happen when a user clicks one item from the lis view
}
});
Page2_sent_msg.setTag("sentMsg");
return Page2_sent_msg;
}
I do really need a help. Kind regards!
Just write the fragment transaction in onclick of refresh button
fragment = new HomeFragment();
onFrangmentChange(fragment, true, false);
onFrangmentChange function will be like this
private void onFrangmentChange(BaseFragment fragment, boolean replace,
boolean addBackstack) {
this.fragment = fragment;
fm = getFragmentManager();
ft = fm.beginTransaction();
if (replace) {
ft.replace(R.id.fragment, fragment);
} else {
ft.add(R.id.fragment, fragment);
}
if (addBackstack) {
ft.addToBackStack(fragment.getClass().getSimpleName());
}
ft.commit();
}
Note:BaseFragment is nothing but A fragment which extend Fragment.You can write the common functions like checking network connection,email validation etc.in this fragment.
Add a method refresh in your fragment like this
public void refreshFragment() {
sentMsgArrayList.clear();
sentMsgAdapter.notifyDataSetChanged();
SQLite_database_helper_class myDb=new SQLite_database_helper_class(getContext());
Cursor result=myDb.getting_sms_from_db();
if (result.moveToFirst()){
do {
if (!result.getString(3).equals("Sent message")){
continue;
}else{
sentMsgArrayList.add("SMS No : "+result.getString(0)+"\n"
+"Address : "+result.getString(1)+"\n"
+"Date : "+result.getString(2)+"\n"
+"Type : "+result.getString(3)+"\n"
+"Content : "+"\n________\n\n"+result.getString(4)+"\n");
}
}while (result.moveToNext());
sentMsgAdapter.notifyDataSetChanged
}
Then called it once the user taps on refresh
#Override
public boolean onOptionsItemSelected(MenuItem item){
Fragment sentMsg=getSupportFragmentManager().findFragmentByTag("fragmentSentMsg");
Fragment receivedMsg=getSupportFragmentManager().findFragmentByTag("fragmentReceivedMsg");
Fragment allMsg=getSupportFragmentManager().findFragmentByTag("fragmentAllMsg");
switch (item.getItemId()){
case R.id.refresher_id:
sentMsg.refreshFragment();
receivedMsg.refreshFragment();
allMsg.refreshFragment();
break;
}
return super.onOptionsItemSelected(item);
}
Related
I have a problem with the back/up button in a Fragment.
I have an Activity in which I have some fragments. In one Fragment, that I call "1", I have a list view. When I click on any item it goes to another fragment "2".
I need functionality such that the back/up button only works in Fragment 2 but not in Fragment 1.
Is there a way this can be done?
I have tried this in the Activity, but I don't understand how can this help:
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
When i change from fragment 1 to fragment 2 i have this code:
fragment = new MaterialesFragment();
FragmentManager fragmentManager3 = getFragmentManager();
fragmentManager3.beginTransaction().replace(R.id.frame, fragment).addToBackStack("tagMateriales").commit();
Thanks a lot :-)
Try to use addToBackStack() method on the FragmentTransaction object you use to replace the fragment2 into the screen:
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment2).addToBackStack("tagHere").commit();
You can pass null as the parameter if you don't need the actual tag.
Please use this code for your 'fragment 2'
public void showFragmentWithoutStack(Fragment fragment, String tag, int id) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.add(id, fragment, tag);
transaction.commitAllowingStateLoss();
}
Where tag might be String class name, id of your root view in activity (Because fragment should appear on the top layer).
There are a lot of way to do this job. In my opinion the most elegant is the following. I would isolate the logic in each component. Every fragment implements an interface like "IBackHandler" that allows activity and fragment to communicate. In the activity onBackPressed asks first the fragment (if it is instantiated) what to do and then acts.
The interface:
public interface IBackHandler {
boolean doBack();
}
The fragment that implements that interface and put its logic to handle the back button pressed:
public class YourFragment1 extends YourBaseFragment implements IBackHandler {
// your code
#Override
public boolean doBack() {
// return true means that you have done your stuff
//and you don't want 'super.onBackPressed()' to be called
return true; // this means do nothing
}
}
Fragment 2:
public class YourFragment2 extends YourBaseFragment implements IBackHandler {
// your code
#Override
public boolean doBack() {
return false; //this means: call 'super.onBackPressed()'
}
}
Your Activity:
public class YourActivity extends YourBaseActivity {
//your code
#Override
public void onBackPressed() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.yourFragment);
if (currentFragment instanceof IBackHandler) {
if (!((IBackHandler) currentFragment).doBack()) {
super.onBackPressed();
}
} else
super.onBackPressed();
}
}
You could think that this is overengineering but I can reassure you that in this way you'll always be able to control what'happening in your flow.
Hope this help!
In order to use the onBackPressed() method override in the Activity as you have in the question, you also need to add this to your Fragment:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Assuming MainActivity is the Activity subclass name
if (getActivity() instanceof MainActivity) {
((MainActivity) getActivity()).onBackPressed();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
In order to show/hide the back button, add these methods to your Activity:
public void showUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void hideUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
Then, when you want to show or hide the back/up button from a Fragment, call these methods.
In your case, you could hide the back/up button from onResume() in Fragment 1:
((MainActivity) getActivity()).hideUpButton();
And then show it in onResume() in Fragment 2:
((MainActivity) getActivity()).showUpButton();
I solved this problem use this code when change fragment:
String fragmentIndexString="fragmenttwo";//or fragmentone something
transaction.addToBackStack();
This is full code in Activity:
FirstFragment firstFragment; // my first fragment
SecondFragment secondFragment; // my second fragment
public static String FIRST="asfasgasg"; //first fragment index
public static String SECOND="gsadgsagd"; //second fragment index
...
/* u can change fragment by using setFragment funiction */
public void setFragment(String page){
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (page){
case FIRST:
if(firstFragment==null) firstFragment= SettingFragment.newInstance();
if (!firstFragment.isAdded()) {
transaction.replace(R.id.fragmentcontainer, firstFragment);
transaction.addToBackStack(INDEX);
transaction.commit();
} else {
transaction.show(firstFragment);
}
break;
case SECOND:
if(secondFragment==null) secondFragment= SettingFragment.newInstance();
if (!secondFragment.isAdded()) {
transaction.replace(R.id.fragmentcontainer, secondFragment);
transaction.addToBackStack(INDEX);
transaction.commit();
} else {
transaction.show(secondFragment);
}
break;
default:
setFragment(INDEX);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
if(fragmentManager.getBackStackEntryCount()>1){
fragmentManager.popBackStack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
I am trying to use backpress on fragments. I am not able to fix it. Here is my code below.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
if (position!=3){
pos = position;
}
switch (position) {
case 0:
fragment = new Profile();
break;
case 1:
fragment = new Products();
break;
case 2:
fragment = new Help();
break;
case 3:
DialogLogout(DrawerFragment.this, getString(R.string.logout), getString(R.string.cofirm_logout));
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(navMenuTitles[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
On Product Fragment I have list in which I again use to call another fragment.
listCards.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new Transactions();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragment)
.remove(Products.this)
.add(R.id.frame_container, fragment) //replace(R.id.frame_container, fragment)
.addToBackStack(null)
.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
return rootView;
}
BackPress functionality on DrawerFragmentActivity is like below:
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
if (count > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
Functionality would be like, DrawerFragmentActivity(Profile page by default)->Product->Transactions. Drawer Icon would be visible on Transactions screen as well, user can click my cards screen again while on transaction screen using drawer.
When user click on product it will again open transactions page, It's working fine. Now what happening is, when we click back on transaction it is coming on Product page, but When I again click on Product list screen(Frame) is overlapping with ProductsList and Transactions screen.
I am sorry if I it's confusing, Please ask if you don't understand. I can explain.
Thanks.
Fragment back press working code
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
Use below code for back pressed in fragment.
public class DashBoard extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish(); }
return true;
}
return false;
}
});
}
this code help you to implement your backpreesed in fragment.
I would recommend you to implement an interface to manage backstack. Here is a good blog post which would help you understand this process
I am using a SlidingTabLayout to implement the sliding tabs. The problem is, when backing from a fragment to the tab fragment, it disappears.
I am going to show the application flow to make things more clear.
First, I call an Activity whithin a Fragment:
public class ScreenSlidePageFragment extends Fragment{
...
public View onCreateView(args...){
...
gridView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
switch(position){
case 0:
Intent intent = new Intent(getActivity(), FrequencyActivity.class);
startActivity(intent);
break;
}
}
}
...
}
}
The code of the FrequencyActivity is below:
public class FrequencyActivity extends AppCompatActivity{
...
protected void onCreate(Bundle savedInstance){
...
toolbar.setNavigationOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
onBackPressed();
}
});
}
final FragmentManager fm = getSupportFragmentManager();
Fragment fragment = Fragment.instantiate(getBaseContext(), "com.example.Fragment.FragmentFrequency");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.home, fragment, "FragFrequency");
fragmentTransaction.addToBackStack("frequency");
fragmentTransaction.commit();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish(); //When there is no back stack, finish the activity
} else {
//Testing purpose
int top = fm.getBackStackEntryCount();
Log.d("BACKSTACK", "Backstack count: " + String.valueOf(top));
Log.d("BACKSTACK", "Backstack name: " + fm.getBackStackEntryAt(top - 1).getName());
}
}
});
}
The FragmentFrequency is the one which contains the SlidingTabLayout, the code can be seen below:
public class FragmentFrequency extends Fragment{
...
//Creates ViewPager adapter
adapter = new ViewPagerAdapter(activity.getSupportFragmentManager(), titles, numOfTabs);
//ViewPager
viewPager = (ViewPager) layout.findViewById(R.id.pager);
viewPager.setAdapter(adapter);
//SlidingTabLayout code
...
}
And finally, the ViewPagerAdapter which loads the Fragments of the tabs
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
...
#Override
public Fragment getItem(int position){
if(position == 0)
return new FragmentTab1();
else
return new FragmentTab2();
}
...
}
For example when the first tab is selected, the FragmentTab1 is loaded, which contains:
Fragment f = Fragment.instantiate(getActivity(), "com.example.Fragment.FragmentLaunchingFrequency");
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.home, f, "FragLaunchingFrequency");
tx.addToBackStack("launchingfrequency");
tx.commit();
The problem is, when the back action is done, the FrequencyActivity loses the reference of the Fragment and it shows a blank. Also, the sliding tabs stop working properly.
Does anyone know how to fix this? I am really out of alternatives.
Thanks
I think you have 2 major questions in your post. Perhaps make another post for the other question.
For now, I can address your question "The problem is, when the back action is done, the FrequencyActivity loses the reference of the Fragment and it shows a blank".
Your code:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.home, fragment, "FragFrequency");
fragmentTransaction.addToBackStack("frequency");
fragmentTransaction.commit();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
...
Notes:
You cannot call addToBackStack() and use OnBackStackChangedListener() in the same FragmentManager. This seems complicated.
Code suggestions:
Remove the use of addOnBackStackChangedListener() and see what happens.
Specific code suggestion:
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish(); //When there is no back stack, finish the activity
} else {
// Call FragmentManager.findFragmentByTag(String tag)
// Call FragmentTransaction.show() after getting the Fragment.
}
}
});
Note: Notice the else block manages the Fragment instead of depending on the BackStack (addToBackStack method).
I have a problem with adding the fragment transactions to the back stack. I have a Main activity in which I populate my layout with a Menu Fragment:
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().add(R.id.frag_container, new MainMenuFragment()).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.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);
}
}
Then, inside the MainMenuFragment, the user chooses some option which results in replacing the menu fragment with some other fragment:
public class MainMenuFragment extends Fragment implements OnItemClickListener{
GridView grid;
FragmentManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main_menu_fragment, container, false);
manager = getActivity().getFragmentManager();
grid = (GridView) root.findViewById(R.id.gridView1);
grid.setAdapter(new MenuTileAdapter(getActivity()));
grid.setOnItemClickListener(this);
return root;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction trans = manager.beginTransaction();
if (position == 0){
trans.replace(R.id.frag_container, new BasicSettingsFragment());
trans.addToBackStack(null);
trans.commit();
}
}
}
For what i understand, this should make it so that when the user presses back button on their device, they will be brought back to the menu fragment, but instead this quits the app. What am i doing wrong?
In your Activity overwrite:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
And probably you need to use in every commited fragment transaction:
FragmentTransaction.addToBackStack(null);
Your code is a mixup, you use ActionBarActivity from appcompat and not using getSupportFragmentManager() and the fragments import should be the appcompat one if you decide to use it. If not, use Activity instead of ActionBarActivity and the simple Fragment import with FragmentManager
Add this to your activity android:configChanges="keyboardHidden|orientation|screenSize"
This will stop your activity from restarting when you rotate.
use setRetainInstance(true) on fragments.
You are not adding the MainMenuFragment to the back stack. You can try this one on your activity:
getFragmentManager().beginTransaction().add(
R.id.frag_container, new MainMenuFragment()).
addToBackStack(null).commit();
When you add or replace a fragment with the FragmentManager, you need to manually add the old fragment to the backstack with addToBackStack() before calling commit().
I have two fragments SearchFragment and CreateFragment in a view pager inside a activity called TicketManagementActivity. Now when the user presses the search button in SearchFragment, I want SearchFragment to be replaced with SearchResultFragment. I should then be able to swipe between SeachResultFragment and CreateFragment in the ViewPager. Also when I press back from SearchResultFragment I should go back to SearchFragment.
Right now, when I press the button I get a blank screen instead of the layout of SearchResultFragment. When I press back I get to SearchFragment but now I have to click the button twice for the blank screen to come. Now after the blank screen comes after the double click, whenever I swipe to CreateFragment tab I get a blank screen instead of CreateFragment layout.
I looked at quite a number of questions on SO but none of them seem to be working for me. Most useful seems to be the first two answers in this question, but the first answer doesn't handle the back press, nor am I able to implement it. The second answer seems very implementable but I get errors which I have mentioned below.
My main TicketManagemementActivity:
public class TicketManagementActivity extends FragmentActivity implements
ActionBar.TabListener {
ViewPager viewPager;
TabsPagerAdapter adapter;
ActionBar actionBar;
String[] tabs={"Search", "Create"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_management);
viewPager=(ViewPager)findViewById(R.id.pager);
actionBar=getActionBar();
adapter=new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for(String tab_name : tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
//removed methods for menu creation and filling and placeholder fragment for brevity on SO
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
My activity_ticket_management.xml which is layout set in onCreate of ticket management activity, just contains the viewpager
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
My TabsPagerAdapter class extending FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new SearchFragment();
case 1:
// Games fragment activity
return new CreateFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Relevant part of my SearchFragment:
public class SearchFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search, container, false);
.
.//some widget initializations
.
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ticket_search_btn: searchSigmaTickets();
break;
}
}
public void searchSigmaTickets(){
.
.
.
.//some operations
.
new SearchAsyncTask().execute();
}
}
private class SearchAsyncTask extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params){
.
.//some more operation
.
}
protected void onPostExecute(Void param){
Fragment newFragment = new SearchResultFragment();
//Here I use getFragmentManager and not getChildFragmentManager
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//HERE I try to replace the fragment. I'm not sure what id to pass, I pass the id of the main veiwpager in ticketmanagement activity
transaction.replace(R.id.pager, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
}
}
If I use getChildFragmentManager instead of getFragmentManager as mentioned in the second answer I get
06-25 06:55:32.045: E/AndroidRuntime(2797): java.lang.IllegalArgumentException: No view found for id 0x7f06003c (com.amberroad.sigmaticket:id/pager) for fragment SearchResultFragment{b2fed358 #0 id=0x7f06003c}
Sorry for the lengthy question, how should I solve this?
Kartik, get ready for a lengthy answer to your lenghty question. Replacing fragments in a viewpager is quite involved but is very possible and can look super slick. First, you need to let the viewpager itself handle the removing and adding of the fragments. What is happening is when you replace the fragment inside of SearchFragment, your viewpager retains its fragment views. So you end up with a blank page because the SearchFragment gets removed when you try to replace it.
The solution is to create a listener inside of your viewpager that will handle changes made outside of it so first add this code to the bottom of your adapter.
public interface nextFragmentListener {
public void fragment0Changed(String newFragmentIdentification);
}
Then you need to create a private class in your viewpager that becomes a listener for when you want to change your fragment. For example you could add something like this. Notice that it implements the interface that was just created. So whenever you call this method, it will run the code inside of the class below.
private final class fragmentChangeListener implements nextFragmentListener {
#Override
public void fragment0Changed(String fragment) {
//I will explain the purpose of fragment0 in a moment
fragment0 = fragment;
manager.beginTransaction().remove(fragAt0).commit();
switch (fragment){
case "searchFragment":
fragAt0 = SearchFragment.newInstance(listener);
break;
case "searchResultFragment":
fragAt0 = Fragment_Table.newInstance(listener);
break;
}
notifyDataSetChanged();
}
There are two main things to point out here: 1)fragAt0 is a "flexible" fragment. It can take on whatever fragment type you give it. This allows it to become your best friend in changing the fragment at position 0 to the fragment you desire. 2) Notice the listeners that are placed in the 'newInstance(listener)constructor. These are how you will callfragment0Changed(String newFragmentIdentification)`. The following code shows how you create the listener inside of your fragment.
static nextFragmentListener listenerSearch;
public static Fragment_Journals newInstance(nextFragmentListener listener){
listenerSearch = listener;
return new Fragment_Journals();
}
You could then call the change inside of your onPostExecute
private class SearchAsyncTask extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params){
.
.//some more operation
.
}
protected void onPostExecute(Void param){
listenerSearch.fragment0Changed("searchResultFragment");
}
}
This would trigger the code inside of your viewpager to switch your fragment at position zero fragAt0 to become a new searchResultFragment. There are two more small pieces you would need to add to the viewpager before it became functional.
One would be in the getItem override method of the viewpager.
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
//this is where it will "remember" which fragment you have just selected. the key is to set a static String fragment at the top of your page that will hold the position that you had just selected.
if(fragAt0 == null){
switch(fragment0){
case "searchFragment":
fragAt0 = FragmentSearch.newInstance(listener);
break;
case "searchResultsFragment":
fragAt0 = FragmentSearchResults.newInstance(listener);
break;
}
}
return fragAt0;
case 1:
// Games fragment activity
return new CreateFragment();
}
Now without this final piece you would still get a blank page. Kind of lame, but it is an essential part of the viewPager. You must override the getItemPosition method of the viewpager. Ordinarily this method will return POSITION_UNCHANGED which tells the viewpager to keep everything the same and so getItem will never get called to place the new fragment on the page. Here's an example of something you could do
public int getItemPosition(Object object)
{
//object is the current fragment displayed at position 0.
if(object instanceof SearchFragment && fragAt0 instanceof SearchResultFragment){
return POSITION_NONE;
//this condition is for when you press back
}else if{(object instanceof SearchResultFragment && fragAt0 instanceof SearchFragment){
return POSITION_NONE;
}
return POSITION_UNCHANGED
}
Like I said, the code gets very involved, but you basically have to create a custom adapter for your situation. The things I mentioned will make it possible to change the fragment. It will likely take a long time to soak everything in so I would be patient, but it will all make sense. It is totally worth taking the time because it can make a really slick looking application.
Here's the nugget for handling the back button. You put this inside your MainActivity
public void onBackPressed() {
if(mViewPager.getCurrentItem() == 0) {
if(pagerAdapter.getItem(0) instanceof FragmentSearchResults){
((FragmentSearchResults) pagerAdapter.getItem(0)).backPressed();
}else if (pagerAdapter.getItem(0) instanceof FragmentSearch) {
finish();
}
}
}
You will need to create a method called backPressed() inside of FragmentSearchResults that calls fragment0changed. This in tandem with the code I showed before will handle pressing the back button. Good luck with your code to change the viewpager. It takes a lot of work, and as far as I have found, there aren't any quick adaptations. Like I said, you are basically creating a custom viewpager adapter, and letting it handle all of the necessary changes using listeners
Here is the code all together for the TabsPagerAdapter.
public class TabsPagerAdapter extends FragmentPagerAdapter{
Fragment fragAt0;
fragmentChangeListener listener = new fragmentChangeListener();
FragmentManager manager;
static String fragment0 = "SearchFragment";
//when you declare the viewpager in your adapter, pass it the fragment manager.
public viewPager(FragmentManager fm) {
super(fm);
manager = fm;
}
private final class fragmentChangeListener implements nextFragmentListener {
#Override
public void fragment0Changed(String fragment) {
//I will explain the purpose of fragment0 in a moment
fragment0 = fragment;
manager.beginTransaction().remove(fragAt0).commit();
switch (fragment){
case "searchFragment":
fragAt0 = SearchFragment.newInstance(listener);
break;
case "searchResultFragment":
fragAt0 = Fragment_Table.newInstance(listener);
break;
}
notifyDataSetChanged();
}
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
//this is where it will "remember" which fragment you have just selected. the key is to set a static String fragment at the top of your page that will hold the position that you had just selected.
if(fragAt0 == null){
switch(fragment0){
case "searchFragment":
fragAt0 = FragmentSearch.newInstance(listener);
break;
case "searchResultsFragment":
fragAt0 = FragmentSearchResults.newInstance(listener);
break;
}
}
return fragAt0;
case 1:
// Games fragment activity
return new CreateFragment();
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
String[] tab = {"Journals", "Charts", "Website"};
switch (position) {
case 0:
return tab[0].toUpperCase(l);
case 1:
return tab[1].toUpperCase(l);
case 2:
return tab[2].toUpperCase(l);
}
return null;
}
public int getItemPosition(Object object)
{
//object is the current fragment displayed at position 0.
if(object instanceof SearchFragment && fragAt0 instanceof SearchResultFragment){
return POSITION_NONE;
//this condition is for when you press back
}else if{(object instanceof SearchResultFragment && fragAt0 instanceof SearchFragment){
return POSITION_NONE;
}
return POSITION_UNCHANGED
}
public interface nextFragmentListener {
public void fragment0Changed(String fragment);
}