简体   繁体   English

从片段中调用Activity的onCreate或onResume方法

[英]call Activities onCreate or onResume method from a fragment

Scenario : 场景:

I have an activity that populates data from sqlite database in a gridview. 我有一个活动,该活动在gridview中填充来自sqlite数据库的数据。 I am calling a fragment from this activity by onItemClick of Gridview : 我通过Gridview的onItemClick从此活动中调用一个片段:

FragmentA a = new FragmentA();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.Main, a, "a").addToBackStack("a");
ft.commit();

And in that fragment, some changes are made in the contents of the cell of the gridview that was selected. 在该片段中,对选定的Gridview的单元格内容进行了一些更改。

Then, as I have added it to backstack, pressing back button will remove the fragment, and in onPauseMethod, the changes are made in the database. 然后,当我将其添加到backstack中时,按“后退”按钮将删除该片段,并在onPauseMethod中在数据库中进行更改。

 @Override
public void onPause() {
    super.onPause();
    tasksDatabaseOperations.updatenote(id, updated_title, updated_note, updated_date, updated_color, protectredBoolean);
}

Now, to make the changes in the gridview of the main activity, adapter.notifyDataSetChanged has to be called which I have called in its onCreate method. 现在,要在主要活动的Gridview中进行更改,必须调用adapter.notifyDataSetChanged,我已在其onCreate方法中对其进行了调用。

But, as it is a fragment, removing it neither call Activities onCreate nor its onResume method. 但是,由于它是一个片段,因此删除它既不会调用Activity onCreate也不会调用其onResume方法。

Any workaround for this situation? 有什么解决方法吗?

更好的方法是,您应该使用所使用的片段中的活动接口编写回调方法,以便当该片段被分离时,该方法将被回调并根据需要进行工作。

您有很多选择,其中之一是使用广播接收器将数据更新从片段发送到主活动。...另一种方式是,您希望将信号从片段更新发送到活动,是在其中创建一个公共静态方法。可以从片段中调用的活动

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

相关问题 调用Activity onResume 时如何调用Fragment 中的方法? (FragmentPagerAdapter) - How to call a method in a Fragment when the Activities onResume is called? (FragmentPagerAdapter) Android:从onResume()调用onCreate() - Android: call onCreate() from onResume() 从GCMIntentService调用onResume()或onCreate() - Call onResume() or onCreate() from GCMIntentService 如何从活动onCreate方法调用片段 - How to call fragment from activity onCreate method 该方法在OnResume()中起作用,但在OnCreate()中不起作用 - Method works in OnResume() but not in OnCreate() 来自不同活动中另一个片段的片段的调用方法 - Call method of a fragment from another fragment in different activities 从片段的onCreate方法调用System.LoadLibrary()是错误的吗? - Would it be wrong to call System.LoadLibrary() from onCreate method of a fragment? 在调用onResume()之后刷新onCreate() - refresh onCreate() after call to onResume() 片段是否调用父活动的onCreate方法? - Does fragment call the onCreate method of parent activity? 如何检测是否从onCreate(),应用程序唤醒或切换活动中调用了onResume()? - How to detect whether onResume() is called from onCreate(), from application wake up or from switch activities?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM