我目前有一些片段都组织在选项卡中,我希望片段 A 调用片段 B 中的方法。所以我知道我需要调用活动,然后调用 B 中的函数,我见过有人提到使用
ExampleFragment fragment = (ExampleFragment)
getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>();
我遇到了一个问题,因为我的片段添加了一个选项卡侦听器而不是片段管理器,所以我不知道如何使用它来调用方法。这是我的标签的添加方式。
public class fifaActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar bar = getActionBar();
bar.setTitle(TourneyName);
bar.setDisplayHomeAsUpEnabled(true);
bar.setIcon(R.drawable.fifa);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.addTab(bar
.newTab()
.setText("Tables")
.setTabListener(
new TabListener<fifa.tables>(this, "tables",
fifa.tables.class)));
bar.addTab(bar
.newTab()
.setText("Knockouts")
.setTabListener(
new TabListener<fifa.knockouts>(this, "tables",
fifa.knockouts.class)));
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex())
}
public static class TabListener<T extends Fragment> implements
ActionBar.TabListener {
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener(Activity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(Activity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = mActivity.getFragmentManager()
.beginTransaction();
ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(),
mArgs);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
任何有关如何从 fifa.tables 片段调用方法到 fifa.knockouts 片段的帮助将不胜感激。
谢谢,奥利