I am new to Android and learning to create fragments in Android by following this
example: Fragment Navigation Drawer
The code between Navigating between Menu Items and Add Navigation Header consists a method getActivity().
As the author didn't mentioned where to paste this code, I pasted in my MainActivity.java file
Is code between Navigating between Menu Items and Add Navigation Header pasted at correct location by me?
In method selectDrawerItem(MenuItem menuItem) there is a comment // Create a new fragment and specify the planet to show based on position
Does author expects me to add something over here.
The project files layout created by me on AndroidStudio is as follow:AndroidStudio Snapshot
You can use:
this Or `MainActivity.this`
Instead of:
getActivity()
An Activity has no getActivity() method.
Fragments have.
Because getActivity() says: "return the Activity which contains me".
And while Framents are contained in Activities, Activities themselves aren't.
It has been clearly pointed out that you cannot use the getActivity() method in an activity. Well, other alternatives apart from the this keyword could be;
Get current activity context : using the getContext()
This method can be called on a View like text view like so textView.getContext(); This will give the context of the activity in which the view is currently hosted in. i.e something like so View.getContext();
Get App-level context : getApplicationContext() this method returns the activity that houses the entire life cycle of the application.
In Fragment it is best to use onAttach() method to get the instance of an Activity attached to it.
here is a sample code:
#Override
public void onAttach (Activity activity) {
super.onAttach(activity);
}
Related
Concise: I am looking for a way to update a view in an activity from a fragment that the activity contains.
In detail: I have a fragment and an activity that contains the fragment. The activity has a navigation drawer and the navigation drawer contains a image view. What I am trying is to update the image view in the navigation drawer when a HTTP GET request returns a response from the fragment; the response contains a URL to where an image loader parses an image for the image view in the navigation drawer.
Given this, I am trying to get an instance of the view in the activity from the fragment, but I am not sure how to do so. Even, I am not sure if I am on the right direction...
I will greatly appreciate any input.
Regards,
Create Interface:
public interface mInterface{
public void updateIMG(String url);
}
Implement this interface inside your activity and Override updateIMG() method.
Inside your fragment what ever you need to call updateIMG() just initiate interface and call a method.
mInterface listener = (mInterface)getActivity();
listener.updateIMG(url);
Then you call this interface method it will run code inside overrided method inside activity.
In case you get Only the original thread that created a view hierarchy can touch its views., try.
Declare view as public which you want to update and then you can access that view from the fragment and can update from there
You can use a LocalBroadCast to send a broadcast from Fragment whenever needed and then receive the broadcast in Activity and do the changes.
You can also implement Activity, Fragment communication through an interface. Refer this link to implement the same.
I need to add a fragment to a view dynamically as it's also inside a fragment (see the answer https://stackoverflow.com/a/6847770/811405).
The whole structure is like this:
Fragment
|
|---ViewHolder
|
|---(dynamically added fragment)
In my viewholder, I have access to the view. I've first thought that I could call getContext() and then cast it to activity, then use it's fragment manager to add it. However, getContext returns my Application object, not the activity (it's called on app launch before app is physically on the screen, so maybe the activity hasn't been created yet).
How can I add fragment dynamically on ViewHolder? (of course, without using terrible anti-patterns)
My real problem was inflating the layout from an incorrect context (yup, you guessed right, Application instance) instead of my Activity. I've fixed the code to make it inflate from the Activity, and now getContext returns the activity. I could then get the fragment manager and add the fragment normally.
Ok, so I've a Fragment inside which I use getActivity().getClass().getSimpleName() to get the name of the activity that contains it.
Now, I've a method called sampleMethod() inside that activity, and to call it from the fragment I use ((MyActivity) getActivity()).sampleMethod(); This works fine as well.
My question is that how can I use the activity name in the statement ((MyActivity) getActivity()).sampleMethod(); dynamically. Obviously, I do get the name from getActivity().getClass().getSimpleName().
So what I want is something like
`((getActivity().getClass().getSimpleName()) getActivity()).sampleMethod();
Syntactically, the above is incorrect. What's the correct way?
All the Activities that include this fragment should implement an interface, let's say
interface Sample {
public void sampleMethod();
}
then in your fragment
((Sample)getActivity()).sampleMethod();
Using Tabs means using fragments, and for some reason fragments have new steps in their life cycle, like onAttach(Activity).
My fragment fills up some maps from the resources, and it is done on onAttach() instead of the fragment constructor; because in the constructor getResources() throws an exception due to the lack of Activity yet.
The fragment is created on MainActivity like this:
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
switch( tab.getPosition() ) {
case 0:
if( fragmentTab0 == null ) {
fragmentTab0 = new MyFragment();
setTabText(0, ((MyFragment)fragmentTab0).getMyName());
}
fragmentTransaction.add(R.id.fragmentContent, fragmentTab0, "TAB0");
break;
Here lies my problem, in the call to the fragment method getMyName() which uses the maps I mentioned before to get a string. The call to getMyName() is executed before the fragment's onAttach() and the maps are not ready yet.
I am sure I can find a convoluted way to get the name (actually I tried already to pass the activity to the fragment's constructor and built the maps there, and it works, but it goes against the fragment philosophy).
I would have thought that the activity should be visible during Fragment constructor, since the fragments are created from the activity they're going to be eventually attached, so there is no point in delaying the activity attachment.
I also would have thought that the call to new MyFragment() should return after onAttach() is done. But it returns right after the constructor is done.
Therefore I feel not comfortable with the situation and I wonder if I am using fragments the wrong way, if so, the question is, how am I supposed to do it right to be able to call getMyName() there.
Note: From the fragment life cycle diagram it is clear that onAttach() and onDetach() are indistiguishable from onCreate() and onDestroy() respectively, so I question if they are really necessary.
onAttach() is not invoked until the fragment transaction is committed. Until then, a fragment has no reference to the creating Activity unless you pass it such a reference. Passing that reference is probably the cleanest way to implement what you're trying to do.
Generally in Android the title is dictated by the containing activity, not the fragment. For example, a PreferenceActivity's xml headers file lists titles and their associated fragments; those titles do not appear in the preference xml files used by the PreferenceFragment.
An Activity may inflate an arbitrary layout xml that may or may not have a Fragment placeholder in it.
If it does , the Fragment will be instantiated and attached to the Activity.
Is there any way to get a reference to the Fragment from the Activity that has been attached to it ?
FragmentManger.findFragmentById() assumes you know the ID in advance to make it work but in this situation I am proposing, it is not available.
The behavior I'd ideally like to have is that the Activity is aware of any Fragments attaching itself to it so that it may respond to it.
Whenever a fragment is attached to an activity the following callback method is called with the fragment attached as the parameter, you can use it store the reference.
onAttachFragment(Fragment fragment)
http://developer.android.com/reference/android/app/Activity.html#onAttachFragment(android.app.Fragment)