Calling a Fragment method from a parent Activity

2019-01-01 10:54发布

I see in the Android Fragments Dev Guide that an "activity can call methods in a fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag()."

The example that follows shows how to get a fragment reference, but not how to call specific methods in the fragment.

Can anyone give an example of how to do this? I would like to call a specific method in a Fragment from the parent Activity. Thanks.

9条回答
裙下三千臣
2楼-- · 2019-01-01 11:27

If you're using a support library, you'll want to do something like this:

FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment);
fragment.myMethod();
查看更多
倾城一夜雪
3楼-- · 2019-01-01 11:28

I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}
查看更多
何处买醉
4楼-- · 2019-01-01 11:38

you also call fragment method using interface like

first you create interface

interface name{

void methodname();

}

after creating interface you implement interface in your fragment

myfragment extends Fragment implement interfacename

{


@overide
void methodname()
{

}
}

and you create the reference of interface in your activity

class Activityname extends AppCompatActivity
{

Button click;
Myfragment fragment;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

click=findViewById(R.id.button);

fragment=new fragment();

click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               fragment.methodname();
            }
        });

}

}
查看更多
登录 后发表回答