Android 从父 Activity 调用 Fragment 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10903077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:22:38  来源:igfitidea点击:

Calling a Fragment method from a parent Activity

androidandroid-fragments

提问by gcl1

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

我在Android Fragments Dev Guide 中看到,“活动可以通过使用findFragmentById()或使用从 FragmentManager 获取对 Fragment 的引用来调用片段中的方法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.

谁能举例说明如何做到这一点?我想从父 Activity 调用 Fragment 中的特定方法。谢谢。

回答by Dheeresh Singh

not get the question exactly as it is too simple :

没有完全解决这个问题,因为它太简单了:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(); 

Update:For those who are using Kotlin

更新:对于那些使用 Kotlin 的人

var fragment = supportFragmentManager.findFragmentById(R.id.frameLayoutCW) as WebViewFragment
fragment.callAboutUsActivity()

回答by Gene

If you are using “import android.app.Fragment;” Then use either:

如果您使用的是“import android.app.Fragment;” 然后使用:

1)

1)

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name(); 

Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout. OR

其中 R.id.example_fragment 很可能是 xml 布局中的 FrameLayout id。或者

2)

2)

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name(); 

Where FragTagName is the name u specified when u did:

其中 FragTagName 是您在执行时指定的名称:

TabHost mTabHost.newTabSpec(“FragTagName”)


If you are using “import android.support.v4.app.Fragment;” Then use either:

如果您使用的是“import android.support.v4.app.Fragment;” 然后使用:

1)

1)

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name(); 

OR

或者

2)

2)

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name(); 

回答by JDJ

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();

回答by Chintan Shah

  1. If you're not using a support library Fragment, then do the following:
  1. 如果您没有使用支持库 Fragment,请执行以下操作:

((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();

((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();


2. If you're using a support library Fragment, then do the following:


2. 如果您使用的是支持库 Fragment,请执行以下操作:

((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();

((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();

回答by Surjit Singh

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>(); 
}

回答by Bharat Vasoya

From fragment to activty:

从片段到活动:

((YourActivityClassName)getActivity()).yourPublicMethod();

From activity to fragment:

从活动到片段:

FragmentManager fm = getSupportFragmentManager();

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 tagstring when you added your fragment, use findFragmentByTaginstead:

如果您通过代码添加了片段并在添加片段时使用了标签字符串,请改用findFragmentByTag

YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");

回答by Bharat Vasoya

First you create method in your fragmentlike

首先你创建你fragment喜欢的方法

public void name()
{


}

in your activityyou add this

在你的activity你添加这个

add onCreate()method

添加onCreate()方法

myfragment fragment=new myfragment()

finally call the method where you want to call add this

最后调用你想调用的方法添加这个

fragment.method_name();

try this code

试试这个代码

回答by Bharat Vasoya

you also call fragment method using interface like

您还可以使用类似的接口调用片段方法

first you create interface

首先创建界面

public interface InterfaceName {
    void methodName();
}

after creating interface you implement interface in your fragment

创建接口后,您在片段中实现接口

MyFragment extends Fragment implements 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 MyFragment();

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment.methodName();
            }
        });
    }
}

回答by Kishore Reddy

FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 

回答by Mehdi Dehghani

I don't know about Java, but in C#(Xamarin.Android) there is no need to look up the fragment everytime you need to call the method, see below:

我不知道Java,但是在C#(Xamarin.Android) 中,每次需要调用该方法时都不需要查找片段,请参见下文:

public class BrandActivity : Activity
{
    MyFragment myFragment;

    protected override void OnCreate(Bundle bundle)
    {       
        // ...
        myFragment = new MyFragment();      
        // ...
    }

    void someMethod()
    {
        myFragment.MyPublicMethod();
    }
}

public class MyFragment : Android.Support.V4.App.Fragment
{
    public override void OnCreate(Bundle bundle)
    {
        // ...
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
    {
        // ...
    }

    public void MyPublicMethod()
    {
        // ...
    }   
}

I think in Javayou can do the same.

我认为Java你也可以这样做。