0

I'm making android project? I got question. How can I use activity function without extend it. Cause my current java is fragment so I have to extends Fragment. Please help. My code:

    public class Tab1fragment extends Fragment {

    /**
     * @param argsAc
     */
    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.tab1_layout, container, false);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
ArK
  • 19,864
  • 65
  • 105
  • 136
PLorida
  • 103
  • 1
  • 2
  • 10

4 Answers4

1

You can use like:

((YourActivity)getActivity()).yourPublicMethod(params);
savepopulation
  • 11,248
  • 4
  • 53
  • 71
1

As a quick workaround you can use ((YourActivity) getActivity()).yourMethod().

natario
  • 24,414
  • 15
  • 86
  • 151
1

Check here, the official document tells you how to communicate between Activity and Fragment.

SilentKnight
  • 13,435
  • 18
  • 48
  • 78
1

use it this way :

YourActivity myActivity;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    myActivity=(YourActivity)activity;
}

and call your activity methods:

myActivity.method1();
myActivity.method2(arg0);

OR

You can use interface implementation which is recommended by android as explained here.

OR

Here is a much better answer

Community
  • 1
  • 1
Amrut Bidri
  • 6,116
  • 6
  • 34
  • 79