3

我有这个片段适配器:

public class TabsPagerAdapter extends FragmentPagerAdapter {
    private Context context; 

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }


    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Main fragment activity
            return new main();
        case 1:
            // Sensors fragment activity
            return new sensors();
        case 2:
            // Display fragment activity
            return new display();
        case 3:
            // Settings fragment activity
            return new settings();
        }

        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 4;
    }
     }

我正在尝试以这种方式通过双击和吐司来退出后退按钮:

private static final long DOUBLE_PRESS_INTERVAL = 2000000000;
        private long lastPressTime;

        public void onBackPressed() {
             Toast.makeText(context,
             Resources.getSystem().getString(R.string.kilepes_dupla),
             Toast.LENGTH_SHORT).show();

            long pressTime = System.nanoTime();
            if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
                // this is a double click event
                System.exit(0);

            }
            lastPressTime = pressTime;

        }

我不能做的是在吐司中获取上下文,因此我无法展示它。如何修改代码以使其正常工作?谢谢您的回答!

编辑1: 好的,本教程我正在使用: androidhive ,我想在每个选项卡上制作这个退出方法

4

4 回答 4

2

你应该在Activity上下文中(onBackPressed 是 的一种方法) ,Activity所以你应该改变contextthis

于 2013-11-07T10:23:41.380 回答
0

尝试这个:

public class TabsPagerAdapter extends FragmentPagerAdapter {
private Context context; 

public TabsPagerAdapter(FragmentManager fm, Context mContext) { //add Context to contructor
    super(fm);
context = mContext; //pass context
}

@Override
public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Main fragment activity
            return new main();
        case 1:
            // Sensors fragment activity
            return new sensors();
        case 2:
            // Display fragment activity
            return new display();
        case 3:
            // Settings fragment activity
            return new settings();
        }

        return null;
    }

@Override
public int getCount() {

        // get item count - equal to number of tabs
        return 4;
    }
}
于 2016-08-29T20:34:25.790 回答
-1

你必须使用 getActivity()

像这样

         Toast.makeText(getActivity() , ......
于 2013-11-07T10:23:10.643 回答
-2

您可以使用

getActivity()

或者

getActivity().getApplicationContext()
于 2013-11-07T10:31:34.367 回答