gpt4 book ai didi

java - 无法从父 View 调用 fragment 方法

转载 作者:行者123 更新时间:2023-11-30 08:43:40 24 4
gpt4 key购买 nike

我正在尝试从其父 View 调用 fragment 的公共(public)方法,我遵循了 this , this以及 Stack 上的这些问题。但是,当我尝试从父 View 调用它时,我需要的方法不可用。

这是我的代码:

fragment :

public class FirstTabView extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_first_tab_view, container, false);
return rootView;
}

//The method I need to call
public void PostStuff(String caption){
}
}

父 View :(包含主视图寻呼机)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_view);

pager = (ViewPager) findViewById(R.id.mainpager);
mAdapter = new HomePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);

//Getting the Fragment's Tag. o is the Pager's Fragment index. i.e.: The first fragment
String fragment_tag = "android:switcher:" + pager.getId() + ":" + 0;
FirstTabView fragment = (FirstTabView) getSupportFragmentManager().findFragmentByTag(fragment_tag);
fragment. <This is where I need to call the method and pass the parameter> ();
//The method however doesn't appear when I try to reference it
}

我是否从我的父 View 中正确调用了 Fragment 的方法?我做错了什么?

编辑

这是我用来推送 fragment 的适配器:

public class HomePagerAdapter extends FragmentPagerAdapter {

public HomePagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int index) {

switch (index) {
case 0:
return new FirstTabView();
case 1:
return new SecondTabView();
case 2:
return new ThirdTabView();
case 3:
return new FourthTabView();
case 4:
return new FifthTabView();
}

return null;
}

@Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}

}

最佳答案

您可以将 FirstTabView 的引用保存到您的 MainActivity,然后调用 fragment 的方法。

FirstTabView

public class FirstTabView extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_first_tab_view, container, false);
return rootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//set this fragment to your MainActivity
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.setFirstTabView(this);
}


//The method I need to call
public void PostStuff(String caption){

}
}

主 Activity

private FirstTabView firstTabView;
@Override
public void onCreate(Bundle bundle) {
........
if(firstTabView != null) {
firstTabView.PostStuff("Hello World");
}
}

public void setFirstTabView(FirstTabView firstTabView){
this.firstTabView = firstTabView
}

关于java - 无法从父 View 调用 fragment 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com