Android activity get parent view

How to access parent Activity View in Fragment

I have an ActionBarActivity and fragment. I am using FragmentPagerAdapter that provides fragment to my app. My question How can I access parent Activity View in Fragment ??

5 Answers 5

Specifically, the fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout

In Kotlin it is very easy to access parent Activity View in Fragment

At first, create a view like this:

Then convert it to any view that you need like this:

Note that if you are using findViewById<>() from activity, it wont work if you call it from fragment. You need to assign the view to variable. Here is my case

if you are using kotlin then you can use this syntax

Not the answer you’re looking for? Browse other questions tagged android android-fragments fragment or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to get Activity’s content view?

What method should I call to know if an Activity has its contentView (once the method setContentView() has been called)?

8 Answers 8

You can get the view Back if you put an ID to your Layout.

And call it from findViewById .

You may want to try View.getRootView() .

You can also override onContentChanged() which is among others fired when setContentView() has been called.

If you are using Kotlin

There is no «isContentViewSet» method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

If content view was already set, requestWindowFeature will throw an exception.

The best option I found and the less intrusive, is to set a tag param in your xml, like

PHONE XML LAYOUT

TABLET XML LAYOUT

and then call this in your activity class:

Hope it works for u.

Not the answer you’re looking for? Browse other questions tagged android or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

Читайте также:  Прошивка андроид хонор 10 лайт

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Accessing instance of the parent activity?

Suppose i have a class first.java(activity class) and i start another activity in this class (second.java — activity class). How can i access the instance of first.java from second.java ? Can someone give me a good explanation on this.. An example would be great.

5 Answers 5

If you need your second activity to return some data to your first activity I recommend you use startActivityForResult() to start your second activity. Then in onResult() in your first activity you can do the work needed.

In First.java where you start Second.java:

The result method:

If you do not wish to wait for the Second activity to end before you do some work in the First activity, you could instead send a broadcast which the First activity reacts to.

You can simply call getParent() from the child activity.

I have no clue why other answers are so complicated.

Only this should work

first.instance is the required thing that is accessible from the second class

try this if this work 4 u.
something like this.

now from second class call first.getInstance();

you can also directly acess instance in static way like this first.instance.
Thanks.

You can’t create an activity directly. In the first activity take a static activity variable like this,

In the onCreate do this.

Then in the second activity do this,

Edit: For passing data from one activity to other activity this is not the way. Above answer was to get activity instance from other activity which was initially asked.

To pass data from one activity to other activty generally use bundle. But if the data is not primitive data type, then use object class which should implement parcelable or serializable interface. Then through bundle only parcelable list of objects we can pass.

Источник

How to access Fragment’s child views inside fragment’s parent Activity?

I have a supported fragment activity which will load diff fragments. The fragment has some textView with id = «score» and I want to get its handle but findViewById for score’s textView returns null. Why so?

textView is placed in fragment

17 Answers 17

Directly accessing fragment’s views outside fragment is not a good idea. You should use fragment callback interfaces to handle such cases and avoid bugs. The following way works but it is not recommended as it is not a good practice. If you want to access the TextView of Fragment inside its parent Activity then you should define a method inside your Fragment class like this:

Now you can use this inside your Activity like this:

here myFragment is of type MyFragment .

If you want to access the whole TextView then you can define a method like this inside MyFragment.java :

By this you can access the TextView itself.

Hope this Helps. 🙂

It is possible with following way:

Keep reference of inflated view in the Fragment like this :

Create a function in the Activity, like this:

Its purpose is to keep reference of current fragment. Whenever you wanna switch fragment, you call above function, like this (from fragment):

Now you’ve current fragment reference. So you can directly access Fragment’s views in Activity like this: this.fragment.view

Читайте также:  Android tv просмотр iptv

You have no need of reference of Fragment view to get its components in Activity. As you can directly access layout components of a Fragment in parent Activity.

Simply you can access any component by this

In order to access the TextView or Button or whatever in your fragment you need to do the following:

Once that is done in your MainActivity or any other where you want to access your TextView from your Fragment you should make sure to set up the fragment in your OnCreate() method other ways it will most likely throw nullPointer. So your activity where you want to change the TextView should look smth like this:

Hope this helps 🙂

You can access with getView method of Fragment class.

For example You have a TextView in Your MyFragment with id of «text_view»
In Your Activity make a Fragment of Yours:

And when You need a child just call getView and then find Your childView.

Note: if you want the root view of your fragment, then myFragment.getView(); is simply enough.

Just put in fragment instead of putting in activity:

Only doing this:

If your TextView placed inside Fragment that case you cannot access TextView inside your Fragment Parent Activity you can set the interface for intercommunication between Fragment and Activity and send Data when you click on TextView or anyother thing which you want to happend

You can’t access Fragment element in Parent Activity , But You can pass values to your Fragment by following way.

in your onNavigationDrawerItemSelected method of MyActivity do the following

And in MyFragment class create a method called newInstance like following

And in MyFragment ‘s onCreateView() method

That’s All, I hope this will help you. If not please let me know.

The score textView is in the layout of fragment, it’s not in the layout of the MyActivity, i.e. R.layout.activity_home. So you could find the score textview in that fragment once you inflate the corresponding layout file.

It returns null cause the TextView is an element of the Fragment , not the Activity .

Please note that the idea of using Fragment is to encapsulate a module inside the Fragment , which means the Activity should not have direct access to it’s properties. Consider moving your logic where you get the TextView reference inside the Fragment

Simply declare TextView as public in fragment, initialize it by findViewById() in fragment’s onCreateView(). Now by using the Fragment Object which you added in activity you can access TextView.

You need to call method findViewById from your fragment view.

This way works for me.

I suggest you to make the textview part of your activity layout. Alternately you can have the textview as a separete fragment. Have a look at my question here. Its similar to yours but in reverse direction. Here’s a stripped down version of code I used in my project. The explanation are along the code.

The Activity Class

The fragment class:

Communication from activity to fragment is straight forward. This is because activity contains fragment. Keep the fragment object and access its property via setters and getters or the public fields inside it. But communication from fragment to activity requires an interface.

Читайте также:  Смайлики сердечки для андроид

Источник

Different ways to get Context in Android

Context is one of the important and most used property. You need Context to perform a lot of things on Android. Be is displaying a toast or Accessing database, you use context a lot while building Android app.

Context is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. It contains information about what Views are there, How they are laid out etc.

So, it is important to know different types of Context and methods you can call to get context. Lets get started.

The “this” Keyword

The this keyword in general sense refers to current class instance. So, when use “this” keyword inside an Activity, it refers to that Activity instance. And as Activity is subclass of “Context”, you will get context of that activity.

If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or this@MainActivity (Kotlin)

Get current activity context : View.getContext()

This method can be called on a View like textView.getContext() . This will give the context of activity in which the view is currently hosted in.

Get App-level context : getApplicationContext()

If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. you can use this.

So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application.

You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext()

Get Original context : getBaseContext()

This method is only useful when you are using ContextWrapper. You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext()

( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context)

Get Context from Fragment : getContext()

When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in.

Get parent Activity : getActivity()

You can get the parent activity from a Fragment by calling getActivity() .

💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context. Except for some cases, for example when using ContextWrapper, getContext() and getActivity() can point to different contexts.

Non-nullable Context : requireContext() and requireActivity()

These methods are same but “NotNull” versions of getContext() and getActivity() respectively. Usually, if a fragment is detached from Activity, you will get “null” value when you call getContext() or getActivity() . So even when you are sure the context won’t be null, you still have to add null checks (especially in Kotlin) because they return Nullable type.

But requireContext() and requireActivity() will throw IllegalStateException instead of returning null, if there is no context.

These methods are mainly useful when you using Kotlin and you need a Non-Nullable Context. So using these methods instead, is matter of personal preference.

So, did you learn something new? If you did, please clap and share the post. 😄

Источник

Оцените статью