在Android中单击图像时,我的左右滑动不起作用?

时间:2013-11-15 04:39:09

标签: android

 public class Starter_info extends Activity implements OnClickListener,
    OnRatingBarChangeListener {
private GestureDetector gestureDetector;
ImageView iv;
ImageView ib_dow, ib_wal;
ImageView btn_rate;
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
Dialog rankDialog;
RatingBar ratingBar,pre_rating;
float cus_rating;
    ProgressDialog progDailog;
    private static final String TAG_CONTACTS = "Demo";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_RATING = "Rating";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_IMAGE = "Images";
private static final String TAG_DOWNLOAD = "Downloads";
private static int poster_position;
private Bundle poster_description_bundle;
private FetchWallPaperDescriptionTask fetchWallPaperDescriptionTask;
private ImageLoader imgLoader;
private DisplayImageOptions options;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.starter_info);
    Log.v("starter Info Heap","Max Mem in MB:"+(Runtime.getRuntime().maxMemory()/1024/1024));
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    gestureDetector = new GestureDetector(new SwipeGestureDetector());
    imgLoader = ImageLoader.getInstance();
    options= new DisplayImageOptions.Builder()
    .showImageOnLoading(R.drawable.empty_photo)
    .showImageForEmptyUri(R.drawable.empty_photo)
    .showImageOnFail(R.drawable.empty_photo)
    .cacheInMemory(true)
    .cacheOnDisc(true)
    .displayer(new RoundedBitmapDisplayer(20))
    .build();
    ImageView rankBtn = (ImageView) findViewById(R.id.btn_starter_info_rate);
    ib_dow = (ImageView) findViewById(R.id.ib_starter_info_down);
    ib_wal = (ImageView) findViewById(R.id.ib_starter_info_Wall);
    pre_rating=(RatingBar) findViewById(R.id.rb_starter_info_pre_rating);
    iv = (ImageView) findViewById(R.id.iv_starter_info);
rankBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            rankDialog = new Dialog(Starter_info.this,
                    R.style.FullHeightDialog);
            rankDialog.setContentView(R.layout.rating_bar);
            rankDialog.setCancelable(true);
            ratingBar = (RatingBar) rankDialog
                    .findViewById(R.id.dialog_ratingbar);
            float userRankValue = 0;
    ratingBar
                    .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
                        @Override
                        public void onRatingChanged(RatingBar ratingBar,
                                float rating, boolean fromUser) {
                            // TODO Auto-generated method stub
                            cus_rating = rating;

                        }
                    });
  Button updateButton = (Button) rankDialog
                    .findViewById(R.id.rank_dialog_button);
            updateButton.setOnClickListener(new View.OnClickListener()   {
                @Override
                public void onClick(View v) {
                    Toast.makeText(Starter_info.this,
                            "Rating is" + cus_rating,   Toast.LENGTH_LONG)
                            .show();

                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://vaibhavtech.com/work/android/rating.php");
     try {
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                                1);
                        nameValuePairs.add(new BasicNameValuePair("id",
                                (String) MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("id")));
                        nameValuePairs.add(new BasicNameValuePair("rating",
                                "" + cus_rating));
                        httppost.setEntity(new UrlEncodedFormEntity(
                                nameValuePairs));
                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        String response = httpclient.execute(httppost,
                                responseHandler);
    String reverseString = response;
                        Log.i("response", reverseString);

                    } catch (ClientProtocolException e) {
                        Log.i("CPE response ", e.toString());

                    } catch (IOException e) {
                        Log.i("IOException response ", e.toString());
                }
        rankDialog.dismiss();
                }
            });
            rankDialog.show();
        }
    });

    if(getIntent().getExtras()!=null)
        poster_position= getIntent().getExtras().getInt("clicked_position");

    ib_dow.setOnClickListener(this);
    ib_wal.setOnClickListener(this);
    int loader = R.drawable.load;
    fetchWallPaperDescriptionTask=new FetchWallPaperDescriptionTask();
    fetchWallPaperDescriptionTask.execute();
}
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
  @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch(item.getItemId())
    {
    case android.R.id.home:
        onBackPressed();
        return true;
        case R.id.home:
            Intent intent = new Intent(this, Category.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ib_starter_info_down:

           //           showProgress(img_url);
        showProgress((String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("flag_path"));

        new Thread(new Runnable() {
            public void run() {
                downloadFile();
            }
        }).start();
        break;
    case R.id.ib_starter_info_Wall:
          //            showProgress(img_url);
        showProgress((String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("flag_path") );

        new Thread(new Runnable() {
            public void run() {
                downloadFile_Wall();
                WallpaperManager myWallpaperManager = WallpaperManager
                        .getInstance(getApplicationContext());
                Bitmap o = BitmapFactory.decodeFile("/sdcard/." + (String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("title"));
                try {
                    myWallpaperManager.setBitmap(o);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        break;
    case R.id.btn_starter_info_rate:
 break;
    }
}
  @Override
public void onRatingChanged(RatingBar ratingBar, float rating,
        boolean fromUser) {
Toast.makeText(this, "Your Rating is" + rating, Toast.LENGTH_LONG)
            .show();
}
     void downloadFile() {

    try {
      URL url = new URL((String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("flag_path"));
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
     File SDCardRoot = new  File(Environment.getExternalStorageDirectory().toString()+"/wallpaperapp/");
        SDCardRoot.mkdir();
File file = new File(SDCardRoot, (String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("title")+".jpg");
  FileOutputStream fileOutput = new FileOutputStream(file);
     InputStream inputStream = urlConnection.getInputStream();
     totalSize = urlConnection.getContentLength();
   runOnUiThread(new Runnable() {
            public void run() {
                pb.setMax(totalSize);
            }
        });
         byte[] buffer = new byte[1024];
        int bufferLength = 0;
       while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setProgress(downloadedSize);
                    float per = ((float) downloadedSize / totalSize) * 100;
                    cur_val.setText("Downloaded " + downloadedSize
                            + "KB / " + totalSize + "KB (" + (int) per
                            + "%)");
                }
            });
        }
        fileOutput.close();
        runOnUiThread(new Runnable() {
            public void run() {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://vaibhavtech.com/work/android/downloads.php");

                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                nameValuePairs
                    .add(new BasicNameValuePair("id", (String) MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("id")));

                    httppost.setEntity(new UrlEncodedFormEntity(
                            nameValuePairs));
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    String response =   httpclient.execute(httppost,
                            responseHandler);
      String reverseString = response;
                    Log.i("response", reverseString);
       } catch (ClientProtocolException e) {
                    Log.i("CPE response ", e.toString());
                } catch (IOException e) {
                    Log.i("IOException response ", e.toString());
                }
                dialog.dismiss();
                Toast.makeText(Starter_info.this, "SuccessFully Download..",
                        Toast.LENGTH_LONG).show();
            }
        });

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);
        e.printStackTrace();
    } catch (final Exception e) {
        showError("Error : Please check your internet connection " + e);
    }
}

// For WallPaper Set Clcik Here.............
void downloadFile_Wall() {
    try {
        //          URL url = new URL(img_url);
        URL url = new URL((String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("flag_path"));
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        // connect
        urlConnection.connect();
        // set the path where we want to save the file
  //            File SDCardRoot = Environment.getExternalStorageDirectory();
        File SDCardRoot = new File(Environment.getExternalStorageDirectory().toString()+"/wallpaperapp/");
        SDCardRoot.mkdir();
        // create a new file, to save the downloaded file
 //         File file = new File(SDCardRoot, "." + img_name);

        File file = new File(SDCardRoot, (String)MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("title")+".jpg");
        FileOutputStream fileOutput = new FileOutputStream(file);
        // Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();
        // this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        runOnUiThread(new Runnable() {
            public void run() {
                pb.setMax(totalSize);
            }
        });
        // create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setProgress(downloadedSize);
                    float per = ((float) downloadedSize / totalSize) * 100;
                    cur_val.setText("Please Wait...");
                }
            });
        }
        // close the output stream when complete //
        fileOutput.close();
        runOnUiThread(new Runnable() {
            public void run() {
                // pb.dismiss(); // if you want close it..
                Toast.makeText(Starter_info.this, "Changes Apply SuccessFully..",
                        Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);
        e.printStackTrace();
    } catch (final Exception e) {
        showError("Error : Please check your internet connection " + e);
        e.printStackTrace();
    }
}

void showError(final String err) {
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(Starter_info.this, err, Toast.LENGTH_LONG)
                    .show();

        }
    });
   }

void showProgress(String file_path) {
    dialog = new Dialog(Starter_info.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");

    TextView text = (TextView) dialog.findViewById(R.id.tv1);
    text.setText("Downloading file from ... " + file_path);
    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();

    pb = (ProgressBar) dialog.findViewById(R.id.progress_bar);
    pb.setProgress(0);
    pb.setProgressDrawable(getResources().getDrawable(
            R.drawable.green_progress));

    Toast.makeText(getApplicationContext(), "Please Wait..Process Run In BackGround", Toast.LENGTH_LONG).show();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (gestureDetector.onTouchEvent(event)) {
        return true;
    }
    return super.onTouchEvent(event);
}

private void onLeftSwipe() {
  Log.i("Swipe", "Left Swipe");
Toast.makeText(Starter_info.this, "Left Swipe", Toast.LENGTH_LONG).show();
        startActivity(new Intent(Starter_info.this, Starter_info.class));
    JSONArray contacts = null;
Swipe_parser jParser = new Swipe_parser();

    // getting JSON string from URL
   //       String url="http://vaibhavtech.com/work/android/wallpaper_data.php?next="+img_id;
    String url="http://vaibhavtech.com/work/android/wallpaper_data.php?next="+(String) MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("id");
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String title = c.getString(TAG_TITLE);
            String rating = c.getString(TAG_RATING);
            String image = c.getString(TAG_IMAGE);
            String category = c.getString(TAG_CATEGORY);
            String download=c.getString(TAG_DOWNLOAD);
            Log.i("id", id);
            Log.i("titleq", title);
            Log.i("rating", rating);
            Log.i("image",image);
            Log.i("catet", category);
            Log.i("download", download);

        }
        startActivity(new Intent(Starter_info.this,Starter_info.class));
        finish();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

private void onRightSwipe() {
    // Do something

    Log.i("Swipe", "Right Swipe");
    Toast.makeText(Starter_info.this, "Right Swipe", Toast.LENGTH_LONG)
            .show();
    JSONArray contacts = null;

    Swipe_parser jParser = new Swipe_parser();
String url="http://vaibhavtech.com/work/android/wallpaper_data.php?next="+(String) MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("id");
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String title = c.getString(TAG_TITLE);
            String rating = c.getString(TAG_RATING);
            String image = c.getString(TAG_IMAGE);
            String category = c.getString(TAG_CATEGORY);
            String download=c.getString(TAG_DOWNLOAD);
            Log.i("id", id);
            Log.i("titleq", title);
            Log.i("rating", rating);
            Log.i("image",image);
            Log.i("catet", category);
            Log.i("download", download);
           }
        startActivity(new Intent(Starter_info.this,Starter_info.class));
        finish();
    } catch (JSONException e) {
        e.printStackTrace();
    }


 }
 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) {
                Starter_info.this.onLeftSwipe();

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

class FetchWallPaperDescriptionTask extends AsyncTask<String, String, Boolean>
{
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=ProgressDialog.show(Starter_info.this, "", "Loading...");
    }

    @Override
    protected Boolean doInBackground(String... params) {
        JSONArray contacts = null;
        Swipe_parser jParser = new Swipe_parser();
        // getting JSON string from URL
        String url="http://vaibhavtech.com/work/android/wallpaper_data.php?pre="+MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("id");
        Log.v("Description URL", url);
        url="http://vaibhavtech.com/work/android/wallpaper_data.php?pre=4";
        Log.v("Description URL", url);
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);
             poster_description_bundle=new Bundle();
            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String title = c.getString(TAG_TITLE);
                String rating = c.getString(TAG_RATING);
                String image = c.getString(TAG_IMAGE);
                String category = c.getString(TAG_CATEGORY);
                String download=c.getString(TAG_DOWNLOAD);
                Log.i("id", id);
                Log.i("titleq", title);
                Log.i("rating", rating);
                Log.i("image",image);
                Log.i("catet", category);
                Log.i("download", download);

                poster_description_bundle.putString(TAG_ID, c.getString(TAG_ID));
                poster_description_bundle.putString(TAG_TITLE, c.getString(TAG_TITLE));
                poster_description_bundle.putString(TAG_RATING, c.getString(TAG_RATING));
                poster_description_bundle.putString(TAG_IMAGE, c.getString(TAG_IMAGE));
                poster_description_bundle.putString(TAG_CATEGORY, c.getString(TAG_CATEGORY));
                poster_description_bundle.putString(TAG_DOWNLOAD, c.getString(TAG_DOWNLOAD));
                  }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if(progressDialog!=null)
            progressDialog.dismiss();

        if(result)
        {
            imgLoader.displayImage((String) MainActivity.WALL_PAPER_RESPONSE.get(poster_position).get("flag_path"), iv,options);
            Log.v("Image Rating ", poster_description_bundle.getString(TAG_RATING));
            pre_rating.setRating(Float.parseFloat(poster_description_bundle.getString(TAG_RATING)));
            setMemorySpaceUI();
        }
    }
}

private void setMemorySpaceUI()
{
    final TextView occupiedSpaceText = (TextView)findViewById(R.id.occupiedSpace);
    final TextView freeSpaceText = (TextView)findViewById(R.id.freeSpace);
    final TextView downloadCount = (TextView)findViewById(R.id.txt_total_files);
    final ProgressBar progressIndicator = (ProgressBar)findViewById(R.id.indicator);
    final float totalSpace = DeviceMemory.getInternalStorageSpace();
    final float occupiedSpace = DeviceMemory.getInternalUsedSpace();
    final float freeSpace = DeviceMemory.getInternalFreeSpace();
    final DecimalFormat outputFormat = new DecimalFormat("#.##");

    if (null != occupiedSpaceText) {
        occupiedSpaceText.setText(outputFormat.format(occupiedSpace) + " MB");
    }

    if (null != freeSpaceText) {
        freeSpaceText.setText(outputFormat.format(freeSpace) + " MB");
    }

    if (null != progressIndicator) {
        progressIndicator.setMax((int) totalSpace);
        progressIndicator.setProgress((int)occupiedSpace);
    }
    downloadCount.setText("Downloads :"+DeviceMemory.getDownloadCount());
}

 public static class DeviceMemory {

        public static float getInternalStorageSpace() {
  //                StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            //StatFs statFs = new StatFs("/data");
            float total = ((float)statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
            return total;
        }

        public static float getInternalFreeSpace() {
     //             StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            //StatFs statFs = new StatFs("/data");
            float free  = ((float)statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
            return free;
        }

        public static float getInternalUsedSpace() {
 //             StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            if(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/wallpaperapp").isDirectory())
            {
                statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()+"/wallpaperapp");
                //StatFs statFs = new StatFs("/data");
                float total = ((float)statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
                float free  = ((float)statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
                float busy  = total - free;
                return busy;
            }
            else
                return 0;
        }

        public static int getDownloadCount() {
            if(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/wallpaperapp").isDirectory())
                return new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/wallpaperapp").listFiles().length;
            else return 0;
        }
    }

   }

我正在制作一个应用程序,其中我有图像列表,当我选择任何图像,所以变大。然后我想要左右交换。 当我交换我的图像..,它不是swaping.i想要交换我的图像,我该怎么做

1 个答案:

答案 0 :(得分:0)

Try Out this . .I done this some time ago worked fine for me 

public class Swipe extends Activity implements OnClickListener {

ImageView img;

private static final int SWIPE_MIN_DISTANCE = 6; //120;
private static final int SWIPE_MAX_OFF_PATH = 125; //250;
private static final int SWIPE_THRESHOLD_VELOCITY = 100; //200;


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.swipeimage);
    img = (ImageView)findViewById(R.id.image_place_holder);

    gestureScanner = new GestureDetector(this);
   /* 
    img.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(final View view, final MotionEvent event) {
            // TODO Auto-generated method stub
            gdt.onTouchEvent(event);
            //Log.i("Hello my Log 1","How dfgfd are you");
            return true;
        }
    });*/
}



@Override
public void onClick(View v) {

    // TODO Auto-generated method stub

}

  class myClass extends Activity implements OnGestureListener {


    private static final int SWIPE_MIN_DISTANCE = 6; //120;
    private static final int SWIPE_MAX_OFF_PATH = 125; //250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 100; //200;
    private GestureDetector gestureScanner;@
    Override
    public boolean onTouchEvent(MotionEvent me) {
        return gestureScanner.onTouchEvent(me);
    }
    //@Override
    public boolean onDown(MotionEvent e) {
        //viewA.setText("-" + "DOWN" + "-");
        return true;
    }
    //@Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Left Swipe", Toast.LENGTH_SHORT).show();

            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Right Swipe", Toast.LENGTH_SHORT).show();

            } else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Swipe up", Toast.LENGTH_SHORT).show();

            } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Toast.makeText(getApplicationContext(), "Swipe down", Toast.LENGTH_SHORT).show();

            }
        } catch (Exception e) {
            // nothing
        }

        return true;
    }
  /*  @Override
    public void onLongPress(MotionEvent e) {
        Toast mToast = Toast.makeText(getApplicationContext(), "Long Press", Toast.LENGTH_SHORT);
        mToast.show();
    }*/
    //@Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        //viewA.setText("-" + "SCROLL" + "-");
        return true;
    }
    //@Override
    public void onShowPress(MotionEvent e) {
        //viewA.setText("-" + "SHOW PRESS" + "-");
    } //@Override
    public boolean onSingleTapUp(MotionEvent e) {
        Toast mToast = Toast.makeText(getApplicationContext(), "Single Tap", Toast.LENGTH_SHORT);
        mToast.show();
        return true;
    }
    @Override
    public void onGesture(GestureOverlayView arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onGestureCancelled(GestureOverlayView arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onGestureEnded(GestureOverlayView arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onGestureStarted(GestureOverlayView arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

    }
  }
}

希望它可以帮助你: - )