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
  • 20,698
  • 67
  • 109
  • 136
PLorida
  • 103
  • 1
  • 2
  • 11

4 Answers4

1

You can use like:

((YourActivity)getActivity()).yourPublicMethod(params);
savepopulation
  • 11,736
  • 4
  • 55
  • 80
1

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

natario
  • 24,954
  • 17
  • 88
  • 158
1

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

SilentKnight
  • 13,761
  • 19
  • 49
  • 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,276
  • 6
  • 38
  • 80