I want to change the text in text view in fragment1 by clicking a button in fragment2, i managed to do that by declaring the text view as static so i can change the text by Fragment1.textv.setText("hi"); , is that ok and what is the best way to do this.
static textv ;
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_frag_beam_rec, container, false);
textv= (TextView)v.findViewById(R.id.textview);
return v;
}
Most common approach is using interfaces to 'speak' from fragment A to fragment B (you would need to communicate through the activity):
http://developer.android.com/training/basics/fragments/communicating.html
You can also use an Event-bus library like Otto, register the fragments that you want to update, and from the other fragment post an update:
http://square.github.io/otto/
as user3806331 stated you need to use interfaces ,follow the link and you will find what you need.but be aware that having static reference to a widget is a bad practice ,because it may lead to memory leaks in some situations.
Related
I Want to implement multi category in rss feed app, i created a method Downloader which works properly in mainactivity.
But Downloader Method not works in tab fragments.
Here is screenshot of my project and Downloader method.
click here for project screenshot
When i implement downloader method in fragment, it shows an error.
context c is not resolve here
here is code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerview = view.findViewById(R.id.rv);
recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
new Downloader(c,urlAddress,recyclerview).execute();
return view;
}
comment if you need any other information.
You defined in the signature of your class that the first parameter should be context. You try to pass an undefined variable called c in your code thats why c gets highlighted as error. To fix your code either define c or directly pass in an context into the constructor.
You can get the context by calling getContext()and it should work:
new Downloader(getContext(), urlAddress, recyclerview).execute();
I'm working on a "home feed"-like feature where there's a main Fragment with several other fragments added to its layout, making up the content page. I'd like the main fragment class to be able to instanstiate all the fragment classes that inherit from a certain parent fragment class. This way the code would be more dynamic instead of adding a bunch of <fragment> tags to my xml files.
I'm kinda stuck on making up a decent architecture. How would you go on about doing this?
UPDATE:
Here's what I'm basically trying to do, but don't know how:
public class FeedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View parentView = inflater.inflate(R.layout.fragment_home, container, false);
// Get fragments and dynamically add them to
// the FeedFragment's layout
getEntryFragmentsList();
// ...
return parentView;
}
}
public abstract class FeedEntryFragment extends Fragment {
// Somehow add fragment to list of entry fragments
}
public class TestFragment extends FeedEntryFragment {
// Already added to list of entry fragments
}
I don't think that possible to decrease the count of xmls by inheritance. I think you should try to split your xml configurations and use some <merge> or <include> to build the full one from the parts.
May be I can provide more help if you will describe your problem in more details.
You should use FrameLayout to add fragment(s) dynamically by using the FragmentTransaction.
You can also use a ViewPager with tabs or bottom tabs to show multiple fragments. Please check sample from my Dynamic Support library for the complete code.
Abstract fragments
DynamicFragment - Abstract base fragment from the Dynamic support library.
DynamicViewPagerFragment - Abstract fragment which extends the DynamicFragment to implement the ViewPager functionality.
Implementation
HomeFragment - Sample fragment extends the DynamicFragment to implement the home screen.
SettingsFragment - Sample fragment extends the DynamicViewPagerFragment to implement the settings functionality using multiple fragments inside a view pager.
Tutorial Implementation
This better suits your need. TutorialActivity returns a list of fragments to be displayed inside a ViewPager.
DynamicSimpleTutorial generates a DynamicTutorialFragment according to the supplied parameters.
i followed online tutorial on how to create android app.
i want to assign variable in onCreateView, but where is the method?
im using androidstudio latest btw.
please help
For an Activity the sort of equivalent method is onCreate(). You can override onCreateView() in a Fragment.
onCreateView is the method of a Fragment, rathen than an Activity.
As shown in the documentation:
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
Confused, where is onCreateView method in MainActivity?
Nowhere. Activity does not have this method (it's Fragment's). Use onCreate() instead.
create methods in activity is
protected void onCreate(Bundle savedInstanceState) {}
create method in Fragment is
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
I am receiving the following two related errors in eclipse:
1) The method getIntent() is undefined for the type Fragment1
2) The method setDefaultPushCallback(Context, Class<? extends Activity>) in the type PushService is not applicable for the arguments (FragmentActivity, Class<Fragment1>)
Below is the portion of the code where the errors takes place:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container,
false);
ParseAnalytics.trackAppOpened(getIntent());
// inform the Parse Cloud that it is ready for notifications
PushService.setDefaultPushCallback(getActivity(), Fragment1.class);
If you need any clarification, let me know.
1)You cannot call getIntent() inside a Fragment as it's not an Activity and so one does not inherit Activity's methods/ You should try using getActivity().getIntent() if you are really sure that this is what you are looking for.
2)This method asks you for a Context and you are passing it an Activity, and then asks you for a class that extends an activity and you are passing it a fragment. For the first argument i would call getActivity().getApplicationContext() and as a second argument getActivity().
Edit: Try casting the getActivity() like: (Activity) getActivity()
ParseAnalytics.trackAppOpened(((Activity)getActivity()).getIntent());
// inform the Parse Cloud that it is ready for notifications
PushService.setDefaultPushCallback(((Activity)getActivity()).getApplicationContext(), ((Activity)getAcitivty()));
The two problems occur because you passed wrong parameters to them. Changes as following should help you get ride of them:
ParseAnalytics.trackAppOpened(getAcitivty().getIntent());
// inform the Parse Cloud that it is ready for notifications
PushService.setDefaultPushCallback(getActivity(), getActivity());
But, whether this is what you want or not still depends on the needs of that two function.
I need to know, In which fragment callback method, we should call a web service by which after come back to fragment web service should not call again.
For example.
I have a fragment class MyFragment.java
public class MyFragment extends Fragment {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container,
false);
return rootView;
}
}
I need to know which callback method I have to call webservice to update the UI of fragment. Right Now I am calling web services from onCreateView method. but I need to know what should be best way to call web service from fragment.
If I understand your problem correctly, you want to fetch some data from the server and then inform the fragment that data is prepared and redraw the fragment, is that correct? According to the documentation here:
onCreate() -
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
When you create a Fragment somewhere else in your application, onCreate() method is called. When fragment has to be drawn for the first time, onCreateView() is called and this method returns a created View. In your case, you could probably go with something like:
Declare an instance variable (container) for this data and adapter (if you use any).
In onCreate, initialize all this data (empty container), initialize adapter and then execute the AsyncTask.
In onCreateView, prepare the view to return - adapter etc. So now, once AsyncTask will finish, in onPostExecute it calls your_adapter.notifyDataSetChanged(). This will redraw the fragment, since adapter will be informed that data has changed (fetched from the server).
Depends on when you want to fetch the data.
Do you want it every time the app comes to the foreground?
Use onResume()
Do you want it only when the app starts for the first time?
Use onViewCreated(), which gets called after onCreateView is finished.
onCreate() is tricky.
Put everything that you want to call just once in onCreate() method.
For example your API call, list, adapter initialization.
So ideally I would do like this
public void onCreate(Bundle sis) {
getImagesFromServer(); // API Call
initialzeLists()
initializeAdapters()
}
public View onCreateView(LayoutInflater i, ViewGroup c,Bundle sis) {
recyclerView = findViewById()
setUpAdapters()
return rootView;
}
TRICKY PART
But if you really want onCreate() to be called once then reuse Fragment. (Don't create a new instance every time).
How to reuse a Fragment?
While Adding for first time use add it to backStack with a KEY like this
currentFragment = FirstFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
.addToBackStack("FIRST_KEY")
.commit();
And when you want to add it again get the old instance with the KEY like this
currentFragment = getSupportFragmentManager().findFragmentByTag("FIRST_KEY");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
.addToBackStack("FIRST_KEY")
.commit();
Demo project:
Here is the link to a demo project which loads a list of images using the Volley library. It has a similar implementation.
Woof - Use fragments the right way