Call an activity method from a fragment
From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();
From activity to fragment:
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
If you added fragment via code and used a tag
string when you added your fragment, use findFragmentByTag
instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
call method from fragment to Activity
Call method of Activity from fragment
((YourActivityName)getActivity()).addUserLineInfoFragment();
Call method of fragment from Activity
1. Create Interface
public interface OnButtonListener
{
void onButtonClick();
}
2. Init in Activity
protected OnButtonListener onActionButtonListener;
public void setOnButtonListener(OnButtonListener actionButtonListener)
{
this.onActionButtonListener = actionButtonListener;
}
3. In Activity, click event when this action need to perform
this.onActionButtonListener.onButtonClick();
4. Implement listener(OnButtonListener) in Fragment
@Override
public void onButtonClick(){}
5. In fragment onCreateView
((YourActivityName) getActivity()).setOnButtonListener(this);
Calling Activity Method From Inside A Fragment
Use getActivity()
in your fragment.
MyActivity activity = (MyActivity) getActivity();
activity.myMethod();
if you are not sure if your fragment is attached to MyActivity then
Activity activity = getActivity();
if(activity instanceof MyActivity){
MyActivity myactivity = (MyActivity) activity;
myactivity.myMethod();
}
Calling Activity method inside Fragment that is not attached to Activity
First of all, your code is crashing because the Fragment
is not attached to an Activity
. So a quick fix would be to add a null-check like this:
Activity activity = getActivity();
if (activity != null && activity instanceof HomeActivity) {
HomeActivity myactivity = (HomeActivity) activity;
selectedWorkout = myactivity.getSelectedWorkout();
}
That said, accessing the Activity
like this is not a good practice, as it couples the Fragment with a specific Activity
. There are several better ways to approach it, like:
Approach one:
Make the Activity
implement an interface like SelectedWorkoutProvider
, move the getSelectedWorkout() method there and cast to the interface, not to HomeActivity
Approach two:
Pass the selected workout to the Fragment
via arguments, like this:
Bundle args = new Bundle();
args.putString("selected.workout", getSelectedWorkout());
LandingFragment fragment = new LandingFragment();
fragment.setArguments(args);
And then in the Fragment
use:
getArguments().getString("selected.workout");
to get the value.
Approach three:
Use the SharedPreferences
to save the data in the Activity
and later get it in the Fragment
. Please find the documentation for SharedPreferences
here
call activity method from inner viewpager fragments
Yes, it is possible. Follow these steps.
- Make an interface and declare a method.
- Let the activity implement that interface
- Now override the method from interface and write the definition for the function.
- Make the object of the interface in the fragment.
- Using the object call that method whenever needed.
Example using code : -
Inteface Code :-
//use any name
public interface onInputChangeListener {
/*To change something in activty*/
public void changeSomething(//parameters that will hold the new information);
}
Activity Code:-
public class MyActivity extends AppCompatActivity implements onInputChangeListener {
onCreate();
@override
public void changeSomething(/*Arguments with new information*/){
//do whatever this function need to change in activity
// i.e give your defination to the function
}
}
Fragment Code:-
public class MyFragment extends Fragment {
onInputChangeListener inputChangeCallback;
/*This method onAttach is optional*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
inputChangeCallback = (onInputChangeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement onFragmentChangeListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my,container,false);
inputChangeCallback.changeSomething(//pass the new information);
return v;
}
}
This would doo.. Cheers!
If you want a quick Fix :-
In your Fragment:-
public class MyFragment extends Fragment {
MyActivity myActivity;
onCreateView(){
...
myActivity = (MyActivity)getActivity;
myActivity.callAnyFunctionYouWant();
...
}
}
Call Activity's methods from fragment
What you want is a callback interface for the communication from a Fragment to an Activity. The docs already provide a good example for this.
Define an Interface which your Activity implements:
public interface Callback {
void doSomething();
}
public class YourActivity implements Callback {
...
@Override
public void doSomething() {
// your implementation here
}
}
In your Fragment use this interface if one of the Buttons are clicked.
public class ServerFragment extends Fragment {
Callback iCallback;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
iCallback = (Callback) activity;
} catch (ClassCastException e) {
throw new ClassCastException();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.server_layout, container, false);
btnServer = (Button) view.findViewById(R.id.buttonServer);
btnServer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
iCallback.doSomething();
}
});
}
}
With this approach you can leave your logic in the Activity and handle the UI events in the Fragment. Through the events in the Fragment you can invoke the methods in your Activity.
calling fragment method in Activity not working kotlin
This is activity class
class MyActivity : AppCompatActivity() {
private lateinit var myFragment: FirstFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myFragment = FirstFragment()
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, myFragment , "MyFragment")
.commit()
//this is fragment method, we call it from activity
myFragment.getToast(this)
}
}
This is fragment class
class FirstFragment: Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
fun getToast(context: Context) {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
}
Related Topics
Making Textview Scrollable on Android
Why 'Pageradapter::Notifydatasetchanged' Is Not Updating the View
How to Handle Button Clicks Using the Xml Onclick Within Fragments
How to Have Multiple Styles Inside a Textview
Android: View.Setid(Int Id) Programmatically - How to Avoid Id Conflicts
How to Filter a Recyclerview With a Searchview
Fullscreen Activity in Android
How to Avoid Concurrency Problems When Using Sqlite on Android
Error in Launching Avd With Amd Processor
Exception 'Open Failed: Eacces (Permission Denied)' on Android
How to Draw a Path on a Map Using Kml File
Getting the Absolute File Path from Content Uri For Searched Images
How to Display Count of Notifications in App Launcher Icon
How to Detect Orientation Change in Layout in Android