什么事件当选择一个标签片段被触发 [英] What event is triggered when a tab fragment is selected

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

问题描述

我使用的标签片段的活动和动作条承载标签。
我想要做的是,每当出现一个片段(或再次出现)在视图(由用户选择),我开始做一些事情。我不能使用 onResume 在这种情况下,片段的,因为所有的标签都没有真正'暂停'当用户选择另一个选项卡,所以 onResume 不叫

我可以用下面的两个事件从托管活动,但我不想让他们因为我希望片断应该知道自己的这个逻辑,做这个任务。任何想法? TKS。

  @覆盖
    公共无效onTabSelected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
        //当选择给定的标签上,切换到在ViewPager相应页面。
        mViewPager.setCurrentItem(tab.getPosition());
    }    @覆盖
    公共无效onTabReselected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
    }


解决方案

在片段中描述的在这个答案。当该片段是在选定的标签上,setUserVisibleHint()将与真被调用,并且当该片段不是所选标签中,setUserVisibleHint()将与假被调用。这使用支持库为我工作。

  @覆盖
公共无效setUserVisibleHint(布尔isVisibleToUser){
    super.setUserVisibleHint(isVisibleToUser);    如果(isVisibleToUser)
        Log.d(MyFragment,片段是可见的。);
    其他
        Log.d(MyFragment,片段是不可见的。);
}

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

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) {
    }

解决方案

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天全站免登陆