选择选项卡片段时会触发什么事件 [英] What event is triggered when a tab fragment is selected

查看:37
本文介绍了选择选项卡片段时会触发什么事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在活动中使用选项卡片段,操作栏承载选项卡.我想要做的是,每当一个片段出现(或重新出现)在视图中(由用户选择)时,我就开始做一些事情.在这种情况下,我不能使用片段的 onResume,因为当用户选择另一个选项卡时,所有选项卡都不会真正暂停",因此 onResume 不会被调用

I'm using tab fragments in an activity and the actionbar hosts the tabs. What I want to do is that whenever a fragment appears (or re-appears) in the view (selected by the user), I start doing something. I cannot use onResume of the fragment in this case, since all tabs are never really 'paused' when the user selects another tab, so onResume is not called

我可以使用来自托管活动的以下两个事件,但我不想要它们,因为我希望片段应该自己知道这个逻辑并执行该任务.任何的想法?tks.

I can use the two following events from the hosting activity, but I don't want them since I expect the fragment should know this logic on its own and do that task. Any idea? tks.

  @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

推荐答案

在片段中尝试 setUserVisibleHint(),如在这个答案中.当片段在选定的选项卡中时,setUserVisibleHint() 将调用为 true,而当片段不是选定的选项卡时,setUserVisibleHint() 将调用为 false.这对我使用支持库有效.

Try setUserVisibleHint() in the fragment as described in this answer. When the fragment is in the selected tab, setUserVisibleHint() will be called with true, and when the fragment is not the selected tab, setUserVisibleHint() will be called with false. This works for me using the support library.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser)
        Log.d("MyFragment", "Fragment is visible.");
    else
        Log.d("MyFragment", "Fragment is not visible.");
}

这篇关于选择选项卡片段时会触发什么事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆