我如何在片段中的后退按钮上操作。要求电话硬件的后退按钮

时间:2014-10-10 06:22:13

标签: android tabs fragment swipe android-fragmentactivity

我想在主片段类的后退按钮上操作。我在片段的帮助下使用滑动选项卡。所以在par活动类我知道后退按钮的功能。但这对我没有帮助。这是我的代码。我已经完成了动作栏的家庭功能。所以我想和后退按钮一样

               public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Metals","Forex" };
 static int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    i=0;
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

                viewPager.setAdapter(mAdapter);
           //       actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

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

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {

    case android.R.id.home:
        Log.d("back", "backkk");
        i = 1;
        Toast.makeText(getApplicationContext(), "back"+i,100).show();
        onBackPressed();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你想在Fragment

中按下后退键时执行操作

所以在片段

中创建一个公共方法

并从Fragment活动类中覆盖onBackkeypressed调用该方法

例如

@Override
public void onBackPressed() {
    DetailFragment fragment = (DetailFragment) getFragmentManager()
            .findFragmentById(R.id.listfragment);
     fragment.doSomthing()

}