11

So basically i am going to use one Fragment in two different activities.Except one method of fragment in which I want to change something.So how do i get the name of activity which is using the Fragment so that I can do things depending upon the name of which activity is current.

sharin gan
  • 373
  • 1
  • 3
  • 14

7 Answers7

22

in Java try:

getActivity().getClass().getSimpleName() 
  • But be careful when you're using getActivity() method from fragment. If your fragment is not attached to activity getActivity() will return null.

in Kotlin try:

activity?.javaClass?.simpleName
  • It's null safe
savepopulation
  • 11,736
  • 4
  • 55
  • 80
2

The first Ans is great but it's in java so i translate this in koltin

activity?.javaClass?.simpleName
Hamza
  • 2,017
  • 1
  • 19
  • 40
1

Firstly check if the fragment is still attached to activity, then you can check for activity name:

if(isAdded()) {
        getActivity().getClass().getSimpleName();
    }
Saurabh7474
  • 450
  • 5
  • 12
0

Create your own interface and implement it in both of your activity and finally pass this instance to your fragment.

public interface ActivityListener
{
  void onClick();
}

write your code into onClick() method and call this method from fragment.

0

Use this.getClass().getSimpleName() to get the name of the Activity.

if you're in the context of an OnClickListener (or other inner class), specify the class manually:

MainActivity.class.getSimpleName()

for more details check this link

Community
  • 1
  • 1
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
0

I think an better solution will be to create an enum which differentiate your cases and sent that enum through the arguments of the fragment. In this way your cases will be very clear and you will know why there is a difference in the flow of your fragment.

Ionut Negru
  • 6,186
  • 4
  • 48
  • 78
0

If you're in another class and you're trying to get the name of the "initiating class" then you can use Context to access it, like so: getContext().getClass().getSimpleName();

Example:

public String getMyActivityName() {
    String myActivityName;
    myActivityName = getContext().getClass().getSimpleName();
    return myActivityName;
}


@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    Toast.makeText(this.getContext(), "myActiveParentClass: "+getMyActivityName(), Toast.LENGTH_SHORT).show();
}

I hope it helps someone...

Jens
  • 71
  • 1
  • 4