简体   繁体   English

从另一个片段/活动调用片段中的方法

[英]Call method in fragment from another fragment/activity

I made swipe PageView with fragment like that http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/我用这样的片段制作了滑动 PageView http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

Fragment2 have function myUpdate() which updates some data in Fragment2 (data from sql to list). Fragment2 具有函数myUpdate()更新 Fragment2 中的一些数据(从 sql 到列表的数据)。 I could call it easely in Fragment2, but I also need to run myUpdate() from Fragment1 or from other Activity and i don't know how.我可以在 Fragment2 中轻松调用它,但我还需要从 Fragment1 或其他 Activity 运行myUpdate() ,但我不知道如何运行。

I found a few ways but then need R.id.我找到了几种方法,但后来需要 R.id。 * or tag and i have no idea where to find it. *或标记,我不知道在哪里可以找到它。

  FragmentManager fm = getFragmentManager();
  Fragment2 fragment = (Fragment2) fm.findFragmentByTag(<...>);
  fragment.myUpdate();

or same with findViewById ... I suppose I should make some changes in xml, but i don't know what to change... Thanks.或与findViewById相同...我想我应该在 xml 中进行一些更改,但我不知道要更改什么...谢谢。

There are multiple ways to achieve this, one would be local broadcasts.有多种方法可以实现这一点,一种是本地广播。 Implementing a BroadcastReceiver for local broadcasts is exactly the same as for normal broadcasts:为本地广播实现BroadcastReceiver与普通广播完全相同:

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(action != null && action.equals("update")) {
            // perform your update
        }

    }
};

You can register a BroadcastReceiver for your local broadcasts in the first Fragment like this:您可以在第一个Fragment为本地广播注册一个BroadcastReceiver ,如下所示:

LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);

IntentFilter intentFilter = new IntentFilter("update");
// Here you can add additional actions which then would be received by the BroadcastReceiver

broadcastManager.registerReceiver(receiver, intentFilter);

and you can send local broadcasts like this:你可以像这样发送本地广播:

Intent intent = new Intent("update");

LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
broadcastManager.sendBroadcast(intent);

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

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