I'm trying to display a list, using a ListFragment and a custom adapter. Each row includes a TextView and button. It looks like this :
When a button is clicked, I want the element of the list to change. In order to do this, I want to replace the existing ListFragment with another. My problem is that the second fragment is added over the first one, like this :
Here is the code that is executed when I click on a button, in the custom ArrayAdapter :
public void onClick(View view) {
//Some unrelated stuff
//I want to replace the old ListGeneratedFragment by a new one
ListGeneratedFragment fragment = new ListGeneratedFragment();
((MainActivity)getContext())
.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_list_meals, fragment)
.commit();
}
});
I've already used the same technique in other parts of my code, and it works perfectly. I don't understand why the old fragment isn't replaced here.
Related
I've a problem with a proyect I'm creating with Android Studio.
I have a tab layout with two fragments inside and an adapter that show products in a recycler view. The adapter is inside the fragment and is also the one that's responsible for showing the products, but I have the options to sort the list in the activity, and I can't access the adapter from the activity to reorder the list.
This is my code to sort the list,I have this on the model of the product. (I think this is not the problem)
public static Comparator<ProductoModelo> ProductoAZ = new Comparator<ProductoModelo>() {
#Override
public int compare(ProductoModelo p1, ProductoModelo p2) {
return p1.getNombre().compareToIgnoreCase(p2.getNombre());
}
};
And in my Tab activity I have the options in a menu, locate in the toolbar. (This is the problem)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.opciones_ordenar:
Collections.sort(adapterLista.getList(), ProductoModelo.ProductoAZ);
adapterLista.notifyDataSetChanged();
return true;
I know I'm doing something terrible wrong, but I can't see it. How can I access from tab activity to the list on my fragment?
I've tried setting the methods and variables in public and creating the variables in the activity, but it's still not working.
I am loading list view by listview adapter class.
Within that list view I have button called favorite.
ImageButton mFavorite = (ImageButton) convertView.findViewById(R.id.method_fav_btn);
There are multiple image buttons under the same id. I want to identify which button was pressed by means of setting some extra parameters to it. I am doing this for that:
mFavorite.setId(pm.getId());
And on click:
mFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Id is: "+mFavorite.getId());
}
});
But, the problem is, I have 3 items in list view. Every time I am getting same id. How to get different ids on different clicks?
Thanks.
You can use the setTag() + getTag() methods.
See here for a similar question and here for the official documentation.
I have an Android application with a MainActivity and I do this to create navigational tabs in onCreate:
ActionBar myActionBar = getActionBar();
myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = myActionBar.newTab().setText("FirstTab").setIcon(R.drawable.first_tab)
.setTabListener(new TabListener<FirstTabFragment>(this, "FirstTab",
FirstTabFragment.class));
... more tabs ...
The TabListener, I use this from developer.android.com:
http://developer.android.com/reference/android/app/ActionBar.html#newTab():
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
...
public TabListener(Activity activity, String tag, Class<T> clz) { ... }
}
So if a user clicks on the first tab, my fragment FirstTabFragment is called and executes onCreateView.
My problem is, if a user now clicks a button I do the following and I do not know how to switch to the next fragment:
private OnClickListener firstTabListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == button1) {
Intent intent = new Intent(???, MyDetailsFragment.class);
startActivity(intent);
} else if (...) {
...
}
}
};
The MyDetailsFragmentshould show details to the selected item (button click), so I want to drill down to the details fragment and want to give some extra data to the new fragment, so the detail fragment knows which details of which selected item it should display.
The selected tab should not change and the back button should go back to the FirstTabFragment page.
I think I should start a new fragment, but it is not possible, the name of the method startActivity tells me that I start a new activity and not a fragment. So, I have to use the MainActivity and put into there the new fragment?
(I do not use the android-support-v4.jar library, because I only target Android 4 devices)
How can I solve this problem? Any ideas?
From the fragment, call a method on the hosting activity, telling it about the button click event. The activity can then do whatever is appropriate.
Personally, I think that totally replacing the contents of a tab is inappropriate in the vast majority of cases, but you are certainly welcome to do it.
I have searched the numerous questions that look like this one, but haven't found my answer in any of them.
I have an activity that has 3 tabs accessible through the action bar. I achieved this by adding 3 fragments that inflate a custom view I made extending the view class.
At the moment the database changes, I try to refresh the view in my tab by calling invalidate()/postinvalidate(), but this does not work. The same is true for calling onCreateView of the fragment just as many other options I considered.
When I go to another tab and go back, however, the change has been made and my view is updated as it should be.
How can I simulate the same thing that happens when changing to another tab? What does happen. I tried to look at the Fragment lifecycle (tried to call onCreateView()) to figure it out but it just doesn't want to refresh/redraw as it should.
The data is loaded properly, as the data is changed when I change to another tab.
I deleted some of the code as it is no longer relevant. I implemented Cursorloaders instead of my own Observer pattern to notify a change. This is my main activity right now.
The question is what should I do now if I want to redraw the view inside these fragments. If I apply fragmentObject.getView().invalidate() it does not work. I'm having the same problem as before, but now my Observer to notify a change in the database is properly implemented with loaders.
public class ArchitectureActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab EditTab = actionbar.newTab().setText("Edit");
ActionBar.Tab VisualizeTab = actionbar.newTab().setText("Visualize");
ActionBar.Tab AnalyseTab = actionbar.newTab().setText("Analyse");
Fragment editFragment = new EditFragment();
Fragment visualizeFragment = new VisualizeFragment();
Fragment analyseFragment = new AnalyseFragment();
EditTab.setTabListener(new MyTabsListener(editFragment));
VisualizeTab.setTabListener(new MyTabsListener(visualizeFragment));
AnalyseTab.setTabListener(new MyTabsListener(analyseFragment));
actionbar.addTab(EditTab);
actionbar.addTab(VisualizeTab);
actionbar.addTab(AnalyseTab);
ArchitectureApplication architectureApplication = (ArchitectureApplication)getApplicationContext();
architectureApplication.initialize();
getLoaderManager().initLoader(0, null, this);
getLoaderManager().initLoader(1, null, this);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == 0){
return new CursorLoader(this, GraphProvider.NODE_URI , null, null, null, null);
} else if (id == 1){
return new CursorLoader(this, GraphProvider.ARC_URI , null, null, null, null);
}
return null;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Reloading of data, actually happens because when switching to another tab the new data shows up fine
Log.e("Data", "loaded");
}
public void onLoaderReset(Loader<Cursor> loader) {
}
}
Don't try to call onCreateView() yourself... it's a lifecycle method and should be called only by the framework.
Fragments are re-usable UI components. They have their own lifecycle, display their own view, and define their own behavior. You usually don't need to have your Activity mess around with the internal workings of a Fragment, as the Fragment's behavior should be self-contained and independent of any particular Activity.
That said, I think the best solution is to have each of your Fragments implement the LoaderManager.LoaderCallbacks<D> interface. Each Fragment will initialize a Loader (i.e. a CursorLoader if you are using a ContentProvider backed by an SQLite database), and that Loader will be in charge of (1) loading the data on a background thread, and (2) listening for content changes that are made to the data source, and delivering new data to onLoadFinished() whenever a content change occurs.
This solution is better than your current solution because it is entirely event-driven. You only need to refresh the view when data is delivered to onLoadFinished() (as opposed to having to manually check to see if the data source has been changed each time you click on a new tab).
If you are lazy and just want a quick solution, you might be able to get away with refreshing the view in your Fragment's onResume() method too.
I had a similar (although not identical) problem that I could solve in the following way:
In the fragment I added
public void invalidate() {
myView.post(new Runnable() {
#Override
public void run() {
myView.invalidate();
}
});
}
and I called this method from the activity when I wanted to refresh the view myView of the fragment. The use of post() ensures that the view is only invalidated when it is ready to be drawn.
I've found a workaround to refresh the view inside my fragment. I recreated (new CustomView) the view every time the database has been updated. After that I call setContentView(CustomView view). It looks more like a hack, but it works and nothing else that I tried does.
Although my problem was not actually solved, I gave the reward to Alex Lockwood. His advice on Loaders made my application better and it caused me to keep looking for a solution that I eventually found.
I had the same issue.
My solution was detach fragment and attach it again.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment f = getFragment(action);
if(forceUpdate)
{
fragmentTransaction.detach(f);
fragmentTransaction.attach(f);
}
fragmentTransaction.replace(R.id.mainFragment, f);
fragmentTransaction.commit();
currentAction = action;
The fastest solution working for me:
#Override
public void onPause() {
super.onPause();
if (isRemoving() && fragmentView != null) {
((ViewGroup) fragmentView).removeAllViews();
}
}
I'm trying to get the handle on all the new ActionBar and Fragments API.
I have an main activity, and I want it to manage two different tabs.
I'm using the ActionBarSherlock in order to support older version than ICS.
Each tab contains its own Fragment (each one is a subclass of SherlockListFragment)
I got it to work basically nice, but I have a problem that I'm sure that is stupid, but I can't figure it out yet:
On the first time each Fragment is shown, everything is OK, the list is populated and so the MenuItems in the ActionBar.
But the second time you see a tab (After swicth and switch-back), Neither the list get populated, nor the ActionBar MenuItems.
This is how I'm switching the tabs:
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
SherlockListFragment toAttach = // Find the right fragment here...
if (toAttach != null) {
if (toAttach.isAdded() == false) {
transaction.add(R.id.tab_placeholder, toAttach,
REMINDER_FRAGMENT_TAG);
} else {
transaction.attach(toAttach);
}
}
}
And onTabUneselect I'm detaching the Fragment:
#Override
public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
SherlockListFragment toDetach = // Find the right fragment
if (toDetach != null) {
transaction.detach(toDetach);
}
}
I'm populating the lists and the ActionBar menu in onResume:
#Override
public void onResume() {
super.onResume();
setHasOptionsMenu(true);
fillRemindersList();
}
I also tried it in onStart and onCreateView but it didn't help...
So what am I missing here?
And if there are others issues in my code that I'm unaware of, please do tell.
Thanks!
EDIT:
I just confirmed that onResume dosen't get called after I switch tabs, which is definetly wrong since I'm detaching and re-attaching them...
Am I switching tabs the wrong way?
Try using transaction.remove(fragment) in onTabUnselected and transaction.replace in onTabSelected.
Doing the beginTransaction() and commit() outside of this code I assume or did you forget?
You can see a trick used here from the samples as well:
https://github.com/JakeWharton/ActionBarSherlock/blob/master/samples/fragments/src/com/actionbarsherlock/sample/fragments/FragmentTabs.java