0

我有 Fragment ActionBar 选项卡,每个选项卡都附加了一个 TabListener。在我的主要活动中,我得到了一个删除选项卡按钮,如下所示:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()
        case R.id.closeTab:
            closeTab();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void closeTab() {
    if(getActionBar().getTabCount() > 1) {
            Tab tab = getActionBar().getSelectedTab();
            getActionBar().removeTab(tab);
    }
}

我想要完成的是在我的标签片段被删除之前运行一些代码。我可以将它放在片段中,onDestroyView()或者onDestroy()但我只想在按下删除选项卡按钮时运行此代码。我已经检查了文档,TabListener但似乎 TabListener 只听 selectionchanges。我的 TabListener:

public TabListener(Activity a, String t, Class<T> c) {
    activity = a;
    tag = t;
    myClass = c;
}

/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) { 
    // Check if the fragment is already initialized
    if (fragment == null) {
        // If not, instantiate and add it to the activity
        fragment = Fragment.instantiate(activity, myClass.getName());           
        ft.add(android.R.id.content, fragment, tag);

    } else {
        // If it exists, simply attach it in order to show it
        ft.attach(fragment);
    }
}

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

public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

为了澄清我的问题:如何在标签被删除之前在我的片段中运行代码?

4

1 回答 1

0

好的,我在阅读这篇文章后想通了:链接。在我的片段中,我放了setHasOptionMenu(true)

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true); 
}

然后我可以添加onOptionsItemSelected我的片段。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
    case R.id.closeTab:
        closeTab();                
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void closeTab() {
    ActionBar actionBar = getActivity().getActionBar();
    if(actionBar.getTabCount() > 1) {
            Tab tab = actionBar.getSelectedTab();
            actionBar.removeTab(tab);
            Log.d(TAG, "CLOSED TAB");
    }
}
于 2012-08-12T12:00:14.450 回答