Swipe left-right changes activity

十年热恋 提交于 2020-02-02 17:42:30

问题


So I have an activity where I have a Navigation Drawer. I desactivated the swipe to open that Navigation Drawer(it only opens if I click in the button of that menu).

Now I'd like to to do a swipe to change of activity ( like in iPhone).

I've done this, but I'm not sure it's the right way to do it.

Here's my code :

GestureDetectorCompat  mGestureDetector;

EditText etBranche;

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToogle;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modifier_branche);
    setTitle("Mes branches");


    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class
                .getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
    mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);

    mDrawerLayout.addDrawerListener(mToogle);
    mToogle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    NavigationView navigation = (NavigationView)findViewById(R.id.menu_navigation);

    navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {

            switch (item.getItemId())
            {   //si c'est "Mes cours" qui a été choisi
                case R.id.mes_cours:
                    Intent cours = new Intent(ModifierBranche.this,MesCours.class);
                    startActivity(cours);
                    return true;
                case R.id.mes_branches:
                    /
                    finish();
                    startActivity(getIntent());
                    return true;
            }
            return true;

        }
    });
    mGestureDetector = new GestureDetectorCompat(this, new SwipeGestureDetector());

    Intent intent = this.getIntent();
    //si on a réussi à récupérer un intent on fait les tests suivants
    if(intent != null)
    {

        if (option.equals("modifier"))
        {

                String nombranche = intent.getExtras().getString("branche_nom");
                EditText _nombranche = (EditText) findViewById(R.id.ETBranche);
                _nombranche.setText(nombranche);
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //je rajoute le menu que j'ai créé
    getMenuInflater().inflate(R.menu.menu_page_affichage,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if(mToogle.onOptionsItemSelected(item))
    {
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onTouchEvent(MotionEvent event)
{
    mGestureDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}

@Override
protected void onStart() {
    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,findViewById(R.id.menu_navigation));
    super.onStart();
}

private void onLeftSwipe()
{
    Intent intent = new Intent(
        ModifierBranche.this, MesBranches.class);
    startActivity(intent);

}

private void onRightSwipe()
{
    Intent intent = new Intent(
            ModifierBranche.this, PageiTude.class);
    startActivity(intent);

}
// Private class for gestures
private class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
    // Swipe properties, you can change it to make the swipe 
    // longer or shorter and speed
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 200;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            float diffAbs = Math.abs(e1.getY() - e2.getY());
            float diff = e1.getX() - e2.getX();

            if (diffAbs > SWIPE_MAX_OFF_PATH) {
                return false;
            }

            // Left swipe
            if (diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                ModifierBranche.this.onLeftSwipe();

                // Right swipe
            } else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                ModifierBranche.this.onRightSwipe();
            }
        } catch (Exception e) {
            Log.e("YourActivity", "Error on gestures");
        }
        return false;
    }
}



}

回答1:


First make a class as follows

public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener (Context ctx){
    gestureDetector = new GestureDetector(ctx, new GestureListener());
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                    result = true;
                }
            }
            else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    onSwipeBottom();
                } else {
                    onSwipeTop();
                }
                result = true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}

public void onSwipeTop() {
}

public void onSwipeBottom() {
 }
}

And then in your activity. Simply add listener to the layout or object on which you want to listen for gestures event. In my case i have used it on relativeLayout main layout of my activity

relativeLayout = (RelativeLayout) findViewById(R.id.content_main);
    relativeLayout.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
        public void onSwipeTop() {
            Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeRight() {
            Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeLeft() {
            Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeBottom() {
            Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT).show();
        }

    });

Its working :)



来源:https://stackoverflow.com/questions/43584529/swipe-left-right-changes-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!