-1

I tried the solution here:

Calling a Fragment method from a parent Activity

But it didn't work for me.

I have this method in my fragment

 public void showbutton()
    {
        sup.setEnabled(true);
    }

and I'm using this in the parent activity

Fragment fragment = (Fragment) getFragmentManager().findFragmentById(R.id.fragment);
fragment.showbutton();

I'm sure it's a silly mistake, I'm still new to Android so forgive me.

Manan Adhvaryu
  • 323
  • 3
  • 14

4 Answers4

2

Use callback to communicate from fragment to Activity.

public interface UserAction {
void showButton();
}

In the Fragment implement the Interface

@Override
public void showButton() {
        sup.setEnabled(true);
}

Then in your activity just call

UserAction mUserAction = getFragmentManager().findFragmentById(R.id.fragment);
mUserAction.showButton();
pratham kesarkar
  • 3,770
  • 3
  • 19
  • 29
1

Firstly, make sure you are accessing the correct FragmentManager, verify that you need to call either getFragmentManager() or getSupportFragmentManager().

Secondly, you should cast the Fragment to your type. That is,

MyFragment fragment = (MyFragment) getFragmentManager().findFragmentById(R.id.fragment);
fragment.showbutton();
Eric B.
  • 4,622
  • 2
  • 18
  • 33
0

I think you should typecast using Fragment Name.

i.e

YourFragment fragment = (YourFragment) getFragmentManager().findFragmentById(R.id.fragment);
fragment.showbutton();
Avinash Verma
  • 2,572
  • 1
  • 18
  • 22
0

This issue is regarding to fragment life cycle. You are trying to invoke method of fragment which is closed by android OS. You need to create bool in your fragment and set that to false normally but when you need to show button just create that fragment and load that and update your bool to true.Later on check if that bool is true enable your button else disable it. Happy Coding!

Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21