gpt4 book ai didi

android - Null FragmentTransaction 被传递给 TabListener.onTabSelected()

转载 作者:IT王子 更新时间:2023-10-28 23:28:30 25 4
gpt4 key购买 nike

我正在使用此处提供的示例代码将导航选项卡添加到操作栏: http://developer.android.com/guide/topics/ui/actionbar.html我正在使用 ActionBarSherlock。

我的 TabListener 是直接从文档中复制而来的。

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;

/** Constructor used each time a new tab is created.
* @param activity The host Activity, used to instantiate the fragment
* @param tag The identifier tag for the fragment
* @param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}

/* The following are each of the ActionBar.TabListener callbacks */

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}

public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}

我在我的 Activity 中设置了监听器:

    ActionBar.Tab tab = actionBar.newTab();
tab.setText(getString(R.string.TAB_CALC));
tab.setTabListener(new TabListener<StrokeSelectorFragment>(this, "blah", StrokeSelectorFragment.class));
actionBar.addTab(tab);

但应用程序因空指针异常而崩溃,因为空 FragmentTransaction 正在传递给监听器中的 onTabSelected()。我应该在某个地方创建一个吗?

我一遍又一遍地看文档,我很困惑。你能看到我错过了什么吗?

最佳答案

我发现上面 Ollie 的帖子很有帮助,但不够详细。我设法重构了 ActionBar Guide 中提供的代码如下(注意:您必须对 TabListener 中实现的其他方法进行相同的更改):

public void onTabSelected(Tab tab, FragmentTransaction ignoredFt) {
FragmentManager fragMgr = ((FragmentActivity)mActivity).getSupportFragmentManager();
FragmentTransaction ft = fragMgr.beginTransaction();

// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());

ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}

关于android - Null FragmentTransaction 被传递给 TabListener.onTabSelected(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645549/

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