Question

i have this adapter for fragments:

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;
    }
     }

i'm triing to make a back button exit with double tap and toast in this way:

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;

        }

What i can't make is to get the context in the toast, therefore i cant show it. How can i modify the code to get it work? Thank you for your answers!

edit1: okay, this tutorial what i'm using: androidhive and i want to make this exit method on each tab

Was it helpful?

Solution 3

you have to use getActivity()

like this

         Toast.makeText(getActivity() , ......

OTHER TIPS

you should be in the Activity context (onBackPressed is a method of Activity), so you should change context with this

Try this:

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;
    }
}

You may use

getActivity()

or

getActivity().getApplicationContext()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top