hkh114
hkh114

Reputation: 182

how to swipe between activity (where is my code wrong???)

I have 4 activity that have 4 class & xml layout ; i want to swipe between in 4 activity !! i use this code from another post (This Post: Fling gesture detection on grid layout)

i want when touching leftToright Or rightToleft swipe with opening new activity.

where is my code is wrong :

my code :

package com.package110.Y;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log; 
import android.view.MotionEvent;
import android.view.View;

public class ActivitySwipeDetectorActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

 // how to set this 3 line to in my code Or change or update it        

 //ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
 //lowestLayout = (RelativeLayout)this.findViewById(R.id.lowestLayout);
 //lowestLayout.setOnTouchListener(activitySwipeDetector);

   }




    public class ActivitySwipeDetector implements View.OnTouchListener {


            Intent left = new Intent(getApplicationContext(), left.class);
            Intent right = new Intent(getApplicationContext(), right.class);
            Intent top = new Intent(getApplicationContext(), top.class);
            Intent bottom = new Intent(getApplicationContext(), bottom.class);


        static final String logTag = "ActivitySwipeDetector";
        private Activity activity;
        static final int MIN_DISTANCE = 100;
        private float downX, downY, upX, upY;

        public ActivitySwipeDetector(Activity activity){
            this.activity = activity;
        }

        public void onRightToLeftSwipe(){
            Log.i(logTag, "RightToLeftSwipe!");
            activity.startActivity(right);

        }

        public void onLeftToRightSwipe(){
            Log.i(logTag, "LeftToRightSwipe!");
            activity.startActivity(left);
        }

        public void onTopToBottomSwipe(){
            Log.i(logTag, "onTopToBottomSwipe!");
            activity.startActivity(top);
        }

        public void onBottomToTopSwipe(){
            Log.i(logTag, "onBottomToTopSwipe!");
            activity.startActivity(bottom);
        }

        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()){
                case MotionEvent.ACTION_DOWN: {
                    downX = event.getX();
                    downY = event.getY();
                    return true;
                }
                case MotionEvent.ACTION_UP: {
                    upX = event.getX();
                    upY = event.getY();

                    float deltaX = downX - upX;
                    float deltaY = downY - upY;

                    // swipe horizontal?
                    if(Math.abs(deltaX) > MIN_DISTANCE){
                        // left or right
                        if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
                        if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
                    }
                    else {
                            Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
                            return false; // We don't consume the event
                    }

                    // swipe vertical?
                    if(Math.abs(deltaY) > MIN_DISTANCE){
                        // top or down
                        if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
                        if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
                    }
                    else {
                            Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
                            return false; // We don't consume the event
                    }

                    return true;
                }
            }
            return false;
        }

        }



  }

explain: my app is force close !!! my google API is for android 3.0 ; does it have make problem for my app ? and also i try this code and it force close !!!!

another code :

package ir.package110.Y;


 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.GestureDetector;
 import android.view.GestureDetector.SimpleOnGestureListener;
 import android.view.MotionEvent;
 import android.view.View;

 public class ActivitySwipeDetectorActivity extends Activity {
          private GestureDetector gestureDetector;

          @Override
          public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);


              // ...

            gestureDetector = new GestureDetector(new SwipeGestureDetector());
          }

          /* ... */

            Intent right = new Intent(ActivitySwipeDetectorActivity.this.getBaseContext(), right.class);
            Intent left = new Intent(ActivitySwipeDetectorActivity.this.getBaseContext(), left.class);



          private void onLeftSwipe() {
            // Do something
            startActivity(left);

          }

          private void onRightSwipe() {
            startActivity(right);

              // Do something
          }

          // Private class for gestures
          private class SwipeGestureDetector extends 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) {
                    ActivitySwipeDetectorActivity.this.onLeftSwipe();

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

Upvotes: 1

Views: 1526

Answers (2)

Michael
Michael

Reputation: 9824

You should use Fragments. It makes navigation much cleaner.

Fragments run inside of an Activity, and can look and function just like an Activity!

Here is some code.

Activity to hold Fragments

(Tabs and ActionBar can be hidden)

public class Activity extends FragmentActivity implements ActionBar.TabListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.ScoreBoardStyles);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_pager);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab()
                    .setCustomView(t)
                    .setTabListener(this));
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            if (position == 0) {
                fragment = new FirstFragment();
            }
            if (position == 1) {
                fragment = new SecondFragment();
            }
            if (position == 2) {
                fragment = new ThirdFragment();
            }
            if (position == 3) {
                fragment = new FourthFragment();
            }
            return fragment;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
                case 3:
                    return getString(R.string.title_section4).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
            return rootView;
        }
    }

}

Example of a Fragment

public class FirstFragment extends Fragment {

    public ScoreFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.first_layout, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // YOUR CODE HERE
    }
}

If you are using AndroidStudio!

  1. Right click your com.blah.bleh
  2. Go to New
  3. Select create new TabbedActivity (Choose your navigation style towards bottom)

Then create your Fragments

  1. Right click your com.blah.bleh
  2. Go to New
  3. Select Fragment and choose your Fragment type

Set the layout in your Activity class here

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if (position == 0) {
            fragment = new FirstFragment();
        }
        if (position == 1) {
            fragment = new SecondFragment();
        }
        if (position == 2) {
            fragment = new ThirdFragment();
        }
        if (position == 3) {
            fragment = new FourthFragment();
        }
        return fragment;
    }

Hope that helps!

Upvotes: 0

Aerilys
Aerilys

Reputation: 1629

I think the best way to do that is one single Activity and 4 fragments, with a ViewPager.

You can check this link about fragments: http://androidcookbook.com/Recipe.seam;jsessionid=A2DD7A11C804B7C7646DCA883AA452FC?recipeId=1160

And this one about ViewPager: http://developer.android.com/reference/android/support/v4/view/ViewPager.html

Upvotes: 1

Related Questions