从ArrayAdapter中启动FragmentTransaction [英] Start FragmentTransaction from within ArrayAdapter
问题描述
我有一个带有多个行的ListView
.每行都有一个button
.
I have a ListView
with several rows. Each row has a button
.
我希望按钮启动一个FragmentTransaction来替换ListView所在的Fragment.
I want the button to start a FragmentTransaction to replace the Fragment that the ListView is in.
但是,在Adapter
的getView()
方法中,此行不起作用:
However, in the getView()
method of the Adapter
, this line does not work:
FragmentTransaction t = getContext().getSupportFragmentManager().beginTransaction();
它不喜欢上下文.
可以通过这种方式完成交易,还是必须在其他地方进行交易?
推荐答案
getSupportFragmentManager()
仅为类FragmentActivity
定义,而不为Context
定义.因此,如果尝试在Context
类型的对象上调用该编译器,则编译器将无法解析该调用.
getSupportFragmentManager()
is only defined for the class FragmentActivity
, not for Context
. Thus, the compiler can't resolve the call if you try to call it on an object of type Context
.
您可以使用反射来安全地执行此操作.只要您将FragmentActivity作为Context
传递,这将始终有效.注意:FragmentActivity是Context的子类,因此您可以在可以传递Context的任何地方传递FragmentActivity.
You can use reflection to do this in a safe way. This will always work as long as you pass your FragmentActivity as the Context
. Note: FragmentActivity is a subclass of Context, and thus you can pass FragmentActivity wherever you can pass Context.
因此,请改用以下代码:
So use this code instead:
if (getContext() instanceof FragmentActivity) {
// We can get the fragment manager
FragmentActivity activity = (FragmentActivity(getContext()));
FragmentTransaction t = activity.getSupportFragmentManager().beginTransaction();
}
这篇关于从ArrayAdapter中启动FragmentTransaction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!