处理回按片段

时间:2015-04-30 10:04:18

标签: android android-fragments

在我的片段中,我想在背面按一下布局的一个元素的setVisibility。

例如我想要的片段:

 if(list.getVisibility() == View.GONE){

            list.setVisibility(View.VISIBLE);
            text.setVisibility(View.GONE);

  }

但我如何处理片段中的背压事件?并设置此可见性?

更新:

在我的FragmentActivity中,我有:

adapter =  new ViewPagerAdapterEventi(getSupportFragmentManager(),Titles,Numboftabs,mE1,mE2);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);

进入Adaper:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

....

 @Override
    public Fragment getItem(int position) {


        if (position == 0) // if the position is 0 we are returning the First tab
        {


            check = position;
            Fragment1 tab1 = new Fragment1();

            Bundle args = new Bundle();
            args.putString("json", mEv1.toString());
            tab1.setArguments(args);




            return tab1;
        } else {
            Fragment2 tab2 = new Fragment2();
            check = position;
            Bundle args = new Bundle();
            args.putString("json", mEv2.toString());
            tab2.setArguments(args);
            return tab2;
        }


    }

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles.get(position);
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }

}

2 个答案:

答案 0 :(得分:3)

请覆盖FragmentActivity中的方法

@Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();
            Fragment fragment = getSupportFragmentManager().findFragmentByTag("FRAGMENT_TAG");
            fragment.setUserVisibility();
        }

答案 1 :(得分:2)

您必须在活动中处理此问题

@Override
public void onBackPressed() {
    super.onBackPressed();
    MyCustomFragment fragment = (MyCustomFragment) getFragmentManager().findFragmentByTag("TAG_I_USED_WHEN_COMMITTING_FRAGMENT");
    if(fragment != null) {
        fragment.onBackPressed();
    }
}

在MyCustomFragment中创建一个名为onBackPressed()的公共方法,以处理按下后退按钮时应该发生的所有事情。

注意:请不要忘记您的FragmentManager也可以处理onBackPressed事件并从后台堆栈中删除您的片段。这取决于您添加片段的方式