我的结构是什么:
MainActivity.java
MainActivity.java
内ParentFragment.java
ParentFragment.java
内有ChildFragment.Java
ChildFragment.Java
里面有一个适配器
ChildAdapter.java
ChildAdapter.java
内,这是一个名为MyMethod()
现在如何访问MyMethod()
中的MainActivity.java
答案 0 :(得分:1)
这是解决方案
1.通过标签ParentFragment
在MainActivity
中查找ParentFragemnt
2.来自ChildFragment
实例使用getChildSupportManager()
找到ChildAdapter
及其TAG
3.现在在ChildFragment
中创建ChildFragment
变量全局变量并公开
4.从ChildAdapter
实例访问MyMethod()
5.您可以从ChildAdapter
变量
public class Book{
private String title;
private String isbn;
//.... other properties of the book.
//constructors
//getters and setters
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title= title;
}
//do the same for isbn
//overriding toString, equals and hash...
}
public class library{
private List<Book> books = new ArrayList<>();
/* help methods like getCount which get size of books ArrayList, clear method
* which clears the books ArrayList, and other help methods you need.
*/
}
答案 1 :(得分:1)
我通常在Activity中使用此方法,该方法必须替换Fragments:
/**
* This method is used to load the fragment once an item gets selected
*
* @param fragment This is the chosen fragment you want to select
*/
public void loadFragmentActivityFrameLayout(final Fragment fragment) {
// create a transaction for transition here
final FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
// put the fragment in place
transaction.replace(
R.id.frameLayoutId,
fragment,
fragment.getClass().getSimpleName());
// this is the part that will cause a fragment to be added to back stack,
// this way we can return to it at any time using this tag
if(fragment instanceof Fragment1){
transaction.addToBackStack(Fragmen1.class.getSimpleName());
}else if(fragment instanceof Fragment2){
transaction.addToBackStack(Fragment2.class.getSimpleName());
}else if(fragment instance of Fragment3){
transaction.addToBackStack(Fragment3.class.getSimpleName());
}else if(fragment instanceof Fragment4){
transaction.addToBackStack(Fragment4.class.getSimpleName());
}
transaction.commit();
}
然后您可以在该Activity中检索每个Fragment的实例,如下所示:
Fragment1 frag1 =
(Fragment1)getSupportFragmentManager()
.findFragmentByTag(Fragment1.class.getSimpleName());
Fragment2 frag2 =
(Fragment2)getSupportFragmentManager()
.findFragmentByTag(Fragment2.class.getSimpleName());
Fragment3 frag3 =
(Fragment3)getSupportFragmentManager()
.findFragmentByTag(Fragment3.class.getSimpleName());
Fragment4 frag4 =
(Fragment4)getSupportFragmentManager()
.findFragmentByTag(Fragment4.class.getSimpleName());
然后,既然你有一个适配器,让它在片段中公开,让我们说“frag1”,不要忘记让“MyMethod()”也公开进入适配器:< / p>
public CustomAdapter adapter;
最后,您可以从Activity:
中检索任何适配器方法frag1.adapter.MyMethod();
希望我一直很清楚。