Call functions of Activities Belonging to a Fragment

走远了吗. 提交于 2019-11-30 16:45:31

For communication between a Fragment and an activity:

Activity > Fragment:

Call on the public methods of the fragment using this.

TestFragment testFrag = (TestFragment) getFragmentManager().getFragmentById(R.id.testfragment);

if(testFrag != null && testFrag.isAdded())
    testFrag.testMethod("Test");

Fragment > Activity

To send messages to the activity you need to use an interface so in the fragments class add this: (Not in any method)

public interface testInterface{
    public void testMethod(String test);
}

testInterface mCallback;

@Override
public void onAttact(Activity a){
    try{
        mCallback = (testInterface) a;
    }catch(Exception e){
        //TODO
    }
}

then in any method you can go and call this:

mCallback.testMethod("hello");

then for the activity make it so it implements testInterface and import the interface

and then have this method in the activity

@Override
public void testMethod(String testString){

}

:) Just ask for anything more.


Edit

From my first read of your question I thought this is what you wanted sorry, could still cover what you wanted.

I think what your asking for is just a onItemClick method right?

so in the interface you could have

public void onItemClicked(AdapterView<?> parent, View view, int position, long id);

then when onItemClick has been called in the fragment you can use this in it

mCallback.onItemClicked(parent, view, position, id);

and then in the activity, given its implementing the interface you can have

@Override
public void onItemClicked(AdapterView<?> parent, View view, int position, long id){

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!