本文介绍了如何从父Activity访问片段类中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现数据库,因为我需要准备列表或每次进行一些更改时都对其进行更新.我在mainActivity上有一个片段,无法在 MainActivity 中执行操作,因此某些操作将在 MainActivity 中完成,而其他一些操作将在 MainActivity 中完成>片段类.因此,在扩展片段的片段类中,有一个名为 preparelist()的方法,该方法更新数据库并填充数据.在我的主要活动中,我使用默认的 overflow 菜单项执行删除操作,但是在这里,我需要调用 preparelist()方法以显示执行的操作操作或该应用必须关闭才能显示已执行的操作

I am implementing a database as I need to prepare the list or update it everytime I make some changes. I have a fragment on top of mainActivity and I can't perform the operations within the MainActivity so some of the operations are to be done in MainActivity and others in the fragment class.So in the fragment class which extends fragment has a method called preparelist(), which updates the database and populate the data.In my mainactivity I am performing a delete operations using the default overflow menu item, but here I need to call the preparelist() method in order to display the performed operations or the app has to be closed in order to diplay the operation that has been performed

我尝试了以下在网络上的代码

I have tried the following code which is on the web

MyFragment fragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.frag);
( (MyFragment)fragment).prepareList();

但这显示错误

java.lang.NullPointerException: Attempt to invoke virtual method...on a null object reference

推荐答案

解决方案1 ​​

Activity 中调用 Fragment 的公共方法:

MyFragment fragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.frag);
if(fragment != null)
    ( (MyFragment)fragment).prepareList();
else
    Toast.makeText(this, "fragment is null", Toast.LENGTH_SHORT).show();

解决方案2

将删除功能移至片段:

Solution 2

Move the functionality of delete to your fragment:

  1. 在片段中移动删除操作,
  2. 在您的片段中输入:

  1. move your delete operations in your fragment,
  2. in your fragment, write:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);        //this fragment can now override
                                //options menu
}

  • 现在与您在活动中所做的相同,将覆盖 onCreateOptionsMenu() onOptionsItemSelected 等.请注意,方法签名与活动.请参阅片段文档.

  • now do the same as you do in your activity, overriding the onCreateOptionsMenu(), onOptionsItemSelected etc. Please note that the method signatures differ to that of Activity's. See Fragment documentation.

    这篇关于如何从父Activity访问片段类中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 09-04 22:01