如何滑动图像

时间:2011-02-24 07:27:59

标签: android

我正在尝试实现一个简单的图像库,其中我在设备屏幕上一次显示一个图像。当我们从左向右滑动屏幕时,它应显示下一个图像 为此,我实现了一个视图鳍状肢,并为其添加了图像视图 但我不知道如何抓住那次轻扫事件 有人能告诉我一个例子吗?

7 个答案:

答案 0 :(得分:16)

我的应用需要相同的东西,并使用了ViewPagerhttp://blog.sqisland.com/2012/09/android-swipe-image-viewer-with-viewpager.html

之前我使用了ImageSwitcherGestureDetectorhttp://blog.sqisland.com/2012/07/android-swipe-image-viewer.html

使用ViewPager的代码要简单得多,而且体验要好得多,因为当您的手指在屏幕上滑动时,图片会滑动。我直接创建ImageView,不需要任何片段。

答案 1 :(得分:4)

您可以使用ViewPager扩展PagerAdapter ......就像这样

    public class ImageAdapter extends PagerAdapter {
    private Context context;
    private int[] GalImages = new int[] {
            R.drawable.cap8, R.drawable.cap2, R.drawable.cap3, R.drawable.cap1,R.drawable.cap5,
            R.drawable.cap6, R.drawable.cap7, R.drawable.cap9,R.drawable.cap4,
            R.drawable.cap10

    };
    ImageAdapter(Context context)
    {
        this.context=context;
    }

    @Override
    public int getCount() {
        return GalImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = new ImageView(context);
        int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setImageResource(GalImages[position]);
        container.addView(imageView, 0);
        return imageView;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((ImageView) object);
    }
}

xml代码......

 <android.support.v4.view.ViewPager
        android:id="@+id/mvieww"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

答案 2 :(得分:3)

你也可以这样做,不使用视图鳍状肢

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<ImageView
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:layout_gravity="center"
                 android:gravity="center"
                 android:layout_margin="10dip"
                 android:id="@+id/image_place_holder"
                 />

 </RelativeLayout>

活动类

 public class MainActivity extends Activity  {

 private Integer[] mImageIds = { R.drawable.img1, R.drawable.img2,R.drawable.img3 };

private static final String DEBUG_TAG = "MainActivity ";
ImageView imageView;
float startXValue = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.gallery);
    imageView = (ImageView) findViewById(R.id.image_place_holder);
    imageView.setImageResource(mImageIds[num]);
}

@Override
public boolean onTouchEvent(MotionEvent event) {    
    float endXValue = 0;
    float x1 = event.getAxisValue(MotionEvent.AXIS_X);
    int action = MotionEventCompat.getActionMasked(event);
    switch (action) {
        case (MotionEvent.ACTION_DOWN):
            startXValue = event.getAxisValue(MotionEvent.AXIS_X);

            return true;

        case (MotionEvent.ACTION_UP):
            endXValue = event.getAxisValue(MotionEvent.AXIS_X);
            if (endXValue > startXValue) {
                if (endXValue - startXValue > 100) {
                System.out.println("Left-Right");
                imageView.setImageResource(mImageIds[2]);
                }
            }else {
                if (startXValue -endXValue> 100) {
                System.out.println("Right-Left");
                imageView.setImageResource(mImageIds[0]);

                     }
                         }
        return true;


           default:
        return super.onTouchEvent(event);
     }

}

}

答案 3 :(得分:1)

您想使用Android Support Jar中提供的ViewPager。这是一个教程:http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/

您不希望使用Gallery作为一些建议,因为它没有被弃用。但是,从documentation他们建议ViewPagerHorizantleScrollView相对容易地解决此问题:

This class is deprecated.
    This widget is no longer supported. Other horizontally scrolling widgets include
    HorizontalScrollView and ViewPager from the support library.

答案 4 :(得分:1)

你可以这样做,它可以在没有任何视图的情况下工作

public class Swipe extends Activity implements OnClickListener {

private static final int SWIPE_MIN_DISTANCE = 120;
//private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
final GestureDetector gdt = new GestureDetector(new GestureListener());
private GestureDetector gestureDetector;
ImageView img;


View.OnTouchListener gestureListener;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.swipe);
    img = (ImageView)findViewById(R.id.imageView1swipe);

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

并在.java中声明此方法

private class GestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            Log.i("Hello my Log 2","How dfgfd are you");
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                Log.i("dfsd", "Right to left");
                return false; // Right to left
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Left to right
            }

            if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Bottom to top
            } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Top to bottom
            }

            return false;
        }'

可能会this帮助您安排所有图像滑动

答案 5 :(得分:1)

这就是我的成就:

package com.demoimageslider;

import java.util.List;
import java.util.Vector;

import com.nineoldandroids.view.ViewHelper;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class MainActivity extends FragmentActivity {

    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.initialisePaging();
    }

    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Tab1Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab2Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
        this.mPagerAdapter = new PagerAdapter(
                super.getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager) super.findViewById(R.id.pager);
        pager.setAdapter(this.mPagerAdapter);
        pager.setPageTransformer(true, new ZoomOutPageTransformer());
    }

    public static class Tab1Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag1_layout,
                    container, false);
        }
    }

    public static class Tab2Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag2_layout,
                    container, false);
        }
    }

    public static class Tab3Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag3_layout,
                    container, false);
        }
    }

    public static class PagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;

        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }
    }

    public static class ZoomOutPageTransformer implements
            ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.85f;
        private static final float MIN_ALPHA = 0.5f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                // view.setAlpha(0);
                ViewHelper.setAlpha(view, 0);

            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as
                // well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    // view.setTranslationX(horzMargin - vertMargin / 2);
                    ViewHelper.setTranslationX(view, horzMargin - vertMargin
                            / 2);
                } else {
                    // view.setTranslationX(-horzMargin + vertMargin / 2);
                    ViewHelper.setTranslationX(view, -horzMargin + vertMargin
                            / 2);
                }

                // Scale the page down (between MIN_SCALE and 1)
                // view.setScaleX(scaleFactor);
                // view.setScaleY(scaleFactor);
                ViewHelper.setScaleX(view, scaleFactor);
                ViewHelper.setScaleY(view, scaleFactor);

                // Fade the page relative to its size.
                // view.setAlpha(MIN_ALPHA +
                // (scaleFactor - MIN_SCALE) /
                // (1 - MIN_SCALE) * (1 - MIN_ALPHA));

                ViewHelper.setAlpha(view, MIN_ALPHA + (scaleFactor - MIN_SCALE)
                        / (1 - MIN_SCALE) * (1 - MIN_ALPHA));

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                // view.setAlpha(0);
                ViewHelper.setAlpha(view, 0);
            }
        }
    }
}

我使用了nineoldroids库来支持旧版Android的效果。

答案 6 :(得分:0)

为什么不使用gallery widget实现它.....

Here is the gallery tutorial....

感谢......