我正在实现一个数据库,因为我需要准备列表或每次进行一些更改时更新它。我在 mainActivity 之上有一个 fragment ,并且无法在 MainActivity
内执行操作所以有些操作要在MainActivity
中完成和其他人在 fragment class
。
所以在扩展fragment的fragment类中有一个名为preparelist()
的方法,它更新数据库并填充数据。
在我的主要 Activity 中,我使用默认的 overflow
执行删除操作。菜单项,但这里我需要调用preparelist()
方法才能显示已执行的操作,或者必须关闭应用程序才能显示已执行的操作
我尝试了以下网络上的代码
MyFragment fragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.frag);
( (MyFragment)fragment).prepareList();
但这显示错误
java.lang.NullPointerException: Attempt to invoke virtual method...on a null object reference
Basically what I want to know is how do I call the
preparelist()
method within myMainActivity
without making any other abstract class or anything like that
最佳答案
解决方案1
从 Activity
调用 Fragment
的公共(public)方法:
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
将删除功能移至您的 fragment :
- 将删除操作移至 fragment 中,
在您的 fragment 中写入:
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); //this fragment can now override //options menu }
现在执行与您在 Activity 中相同的操作,覆盖
onCreateOptionsMenu()
、onOptionsItemSelected
等。请注意,方法签名与Activity
的。请参阅Fragment文档。
关于java - 如何从父 Activity 访问 fragment 类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910976/