从父Activity调用Fragment方法


124

我在Android Fragments开发指南中看到,“活动可以通过使用findFragmentById()或从FragmentManager获取对Fragment的引用来调用片段中的方法findFragmentByTag()。”

下面的示例显示如何获取片段引用,而不显示如何调用片段中的特定方法。

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

Answers:


210

由于太简单而无法完全得到问题:

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

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

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

10
好的,这很容易,谢谢(我是零碎的新手)。现在最困难的部分是,我似乎一开始无法获得对该片段的引用。它不是在XML布局中定义的,所以我不能使用findFragmentById()。从我所遵循的代码(参见上面的参考)中,我还不清楚片段的创建方式/位置。如果是这样,我可以添加一个标签并使用findFragmentByTag()。该示例的AccountListActivity部分确实调用了beginTransaction()。add(),但根据我的跟踪,从未调用过它。这是我挠头的地方。我感谢任何建议。
gcl1 2012年

34
如何获取片段ID?
Narendra Singh

8
通过这样做,我最终得到一个空对象引用!
Alok Rajasukumaran'7

3
@Fattie,如果我没有片段标签怎么办?
VaclovasRekašiusJr.'Aug

5
我没有在xml中声明片段...所以我没有片段ID,我该怎么办?
akash bs

76

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

1)

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

R.id.example_fragment最可能是xml布局内的FrameLayout ID。要么

2)

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

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

TabHost mTabHost.newTabSpec(“FragTagName”)

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

1)

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

要么

2)

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

1
我有一个ID为R.id.example_fragment的CoordinatorLayout,其返回null。我正在使用import android.support.v4.app.Fragment; 该怎么办?
Kishore

建议您将其发布为新问题,并包括示例代码。如果不查看实际代码,很难说出问题的根源。
基因

9

如果您使用的是支持库,则需要执行以下操作:

FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment);
fragment.myMethod();

4
  1. 如果您不使用支持库片段,请执行以下操作:

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


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

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


3

我认为最好的方法是在调用fragment中的方法之前检查是否添加了fragment。做这样的事情以避免空异常。

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}

2

从片段到活动:

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

从活动到片段:

FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
YourFragmentClass fragment = 
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();

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

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

1

首先,你在你的创建方法fragment一样

public void name()
{


}

在您activity添加此

添加onCreate()方法

myfragment fragment=new myfragment()

最后调用您要调用的方法添加此

fragment.method_name();

试试这个代码


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

1

我不知道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()
    {
        // ...
    }   
}

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


1

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

首先创建界面

public interface InterfaceName {
    void methodName();
}

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

MyFragment extends Fragment implements InterfaceName {
    @overide
    void methodName() {

    }
}

然后在活动中创建接口的引用

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

0
((HomesFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_container)).filterValidation();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.