简体   繁体   English

从活动Android调用片段方法

[英]Calling fragment method from activity Android

I know this issue was discussed many times, but no solution works for me. 我知道这个问题已经讨论了很多次,但是没有解决方案适合我。 I have an activity with fragment attached and using interface I'm calling a method from my activity that is replacing this fragment with another one. 我有一个带有fragmentactivity ,并且使用interface我正在从我的activity中调用一种方法,该方法将这个fragment替换为另一个fragment I want this method also to call a method from my new 'fragment', but however I implement that the application crashes when reaching this point. 我还希望该方法从我的新“片段”中调用一个方法,但是我实现了达到这一点时应用程序崩溃。 Does somebody know a solution for that? 有人知道解决方案吗? I'm new to Android development. 我是Android开发的新手。

public void replacingMethod(String text){

    NewFragment newFragment = new NewFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, newFragment).addToBackStack(null).commit();

    NewFragment f = (NewFragment) getSupportFragmentManager().findFragmentById(R.id.new_fragment);
    f.displayText(text);
}

I've tried to call displayText() from newFragment before and after replacement but it didn't work. 我尝试过在替换前后从newFragment调用displayText() ,但是它不起作用。

尝试使用R.id.fragment_container而不是R.id.new_fragment获取片段。

Your fragment should be attached to the activity to display text. 您的片段应附加到活动中以显示文本。 The right way is to pass the text you want to show to the fragment using it's arguments with Fragment#setArguments(Bundle) and then get it inside fragment using Fragment#getArguments() . 正确的方法是使用Fragment#setArguments(Bundle)的参数将要显示的文本传递给片段,然后使用Fragment#getArguments()将其显示在片段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM