滑动效果像inshorts新闻应用程序

时间:2015-12-03 11:34:32

标签: android android-cardview swipe-gesture

link查看这个新闻应用,我希望像这样开发。

我想要向上/向下滑动副作用..

我尝试了这段代码,但没有像我想的那样正确滑动。 在此代码中,当我向上/向下滑动时,只有文本正在改变而不是布局。

     public class ArticlesActivity extends Activity implements GestureDetector.OnGestureListener{

    ImageView image,imageArticle;
    TextView tv1,tv2,tv3;
    private GestureDetector gd;
    LinearLayout layout;

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

        //Creating GestureDetector Object
        gd = new GestureDetector(this, this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        //Registering TouchEvent with GestureDetector
        return gd.onTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //Destroying Activity
        finish();
    }

    @Override
    public boolean onDown(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

          // TODO Auto-generated method stub
        //Defining Sensitivity
        float sensitivity = 50;
        //Swipe Up Check
        if(e1.getY() - e2.getY() > sensitivity){
            //Setting Image Resource to Up_Arrow on Swipe Up
            tv1.setText("Some Text");
            tv2.setText("Some Text");
            tv3.setText("Some Text");
            image.setImageResource(R.drawable.logo);
            imageArticle.setImageResource(R.drawable.ic_launcher);
            return true;
        }
        //Swipe Down Check
        else if(e2.getY() - e1.getY() > sensitivity){
            //Setting Image Resource to Down_Arrow on Swipe Down

           tv1.setText("Some Text");
            tv2.setText("Some Text");
            tv3.setText("Some Text");
            image.setImageResource(R.drawable.ic_launcher);
            imageArticle.setImageResource(R.drawable.logo);
            return true;
        }
        else{
            //If some error occurrs, setting again to Default_Image (Actually it will never happen in this case)
            image.setImageResource(R.drawable.logo);
            return true;
        }
    }

    @Override
    public void onLongPress(MotionEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
                            float arg3) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onSingleTapUp(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }
}

2 个答案:

答案 0 :(得分:12)

此功能类似于应用

enter image description here

<强> main.xml中

<com.cardviewanimation.VerticalViewPager
    android:id="@+id/verticleViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<强> content_main.xml

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

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="2dp"
    card_view:contentPadding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:src="@drawable/background"
        android:scaleType="fitXY"/>

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"/>
    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

<强> VerticleViewPagerActivity.java

public class VerticleViewPagerActivity extends AppCompatActivity {

VerticalViewPager verticalViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    verticalViewPager = (VerticalViewPager) findViewById(R.id.verticleViewPager);
    verticalViewPager.setAdapter(new VerticlePagerAdapter(this));
  }
}

<强> VerticlePagerAdapter.java

public class VerticlePagerAdapter extends PagerAdapter {

String mResources[] = {"To start off lets understand what exactly Android CardView is? Its a new widget for Android, which can be used to display a card sort of a layout in android. As you may know Android material design is inspired from paper and ink concept. Mostly it displays views on top of each other, with shadows. In simple terms, Android CardView is such a view which has all material design properties, most importantly showing shadows according the elevation. The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of android since it’s available through the Support v7 library. Lets have a look at some of its properties:","To start off lets understand what exactly Android CardView is? Its a new widget for Android, which can be used to display a card sort of a layout in android. As you may know Android material design is inspired from paper and ink concept. Mostly it displays views on top of each other, with shadows. In simple terms, Android CardView is such a view which has all material design properties, most importantly showing shadows according the elevation. The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of android since it’s available through the Support v7 library. Lets have a look at some of its properties:"};

Context mContext;
LayoutInflater mLayoutInflater;

public VerticlePagerAdapter(Context context) {
    mContext = context;
    mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

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

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((LinearLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    View itemView = mLayoutInflater.inflate(R.layout.content_main, container, false);

    TextView label = (TextView) itemView.findViewById(R.id.textView);
    label.setText(mResources[position]);
    container.addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((LinearLayout) object);
}
}

<强> VerticalViewPager.java

 public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    super(context);
    init();
}

public VerticalViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    // The majority of the magic happens here
    setPageTransformer(true, new VerticalPageTransformer());
    // The easiest way to get rid of the overscroll drawing that happens on the left and right
    setOverScrollMode(OVER_SCROLL_NEVER);
}

private class VerticalPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.75f;
    @Override
    public void transformPage(View view, float position) {

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

        }  else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);

            //set Y position to swipe in from top
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // [0,1]
            view.setAlpha(1);

            // Counteract the default slide transition
            view.setTranslationX(view.getWidth() * -position);


            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

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

/**
 * Swaps the X and Y coordinates of your touch event.
 */
private MotionEvent swapXY(MotionEvent ev) {
    float width = getWidth();
    float height = getHeight();

    float newX = (ev.getY() / height) * width;
    float newY = (ev.getX() / width) * height;

    ev.setLocation(newX, newY);

    return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev); // return touch coordinates to original reference frame for any child views
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    return super.onTouchEvent(swapXY(ev));
}
}

答案 1 :(得分:3)

我使用垂直视图寻呼机为您的问题提供了解决方案。我正在分享一些可以满足您目的的代码。

FormatConditionCollection collection = localCell.GetFormatConditions();
......
Int32 conditionIndexN = clN.AddCondition(FormatConditionType.Expression, OperatorType.None, collection[i].Formula1, collection[i].Formula2);

正如您所看到的,上面的类使用DefaultTransformer类进行转换,为实现自定义动画实现ViewPager.PageTransformer,此类代码如下所示

public class VerticalViewPager extends ViewPager {

public VerticalViewPager(Context context) {
    this(context, null);
}

public VerticalViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    setPageTransformer(false, new DefaultTransformer());
}

private MotionEvent swapTouchEvent(MotionEvent event) {
    float width = getWidth();
    float height = getHeight();

    float swappedX = (event.getY() / height) * width;
    float swappedY = (event.getX() / width) * height;

    event.setLocation(swappedX, swappedY);

    return event;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    boolean intercept = super.onInterceptTouchEvent(swapTouchEvent(event));
    //If not intercept, touch event should not be swapped.
    swapTouchEvent(event);
    return intercept;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    return super.onTouchEvent(swapTouchEvent(ev));
}
}

我的活动代码就像这样

public class DefaultTransformer implements ViewPager.PageTransformer {

@Override
public void transformPage(View view, float position) {
    float alpha = 0;
    if (0 <= position && position <= 1) {
        alpha = 1 - position;
    } else if (-1 < position && position < 0) {
        alpha = position + 1;
    }
    System.out.println("alpha--" + alpha);
    view.setAlpha(alpha);
    System.out.println("position--" + position);
    System.out.println("view.getWidth()--" + view.getWidth());
    view.setTranslationX(view.getWidth() * -position);
    float yPosition = position * view.getHeight();
    System.out.println("yPosition---"+yPosition);
    view.setTranslationY(yPosition);
}
}

名为 activity_swipe_layout 的布局就像这样

public class SwipeUpActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipe_layout);
    setTitle("");
    initViewPager();
}
private void initViewPager() {
    VerticalViewPager viewPager = (VerticalViewPager) findViewById(R.id.vertical_viewpager);
    //viewPager.setPageTransformer(false, new ZoomOutTransformer());
    //viewPager.setPageTransformer(true, new StackTransformer());
    String title = "ContentFragment";
    viewPager.setAdapter(new ContentFragmentAdapter.Holder(getSupportFragmentManager())
            .add(ContentFragment.newInstance(title, 1))
            .add(ContentFragment.newInstance(title, 2))
            .add(ContentFragment.newInstance(title, 3))
            .add(ContentFragment.newInstance(title, 4))
            .add(ContentFragment.newInstance(title, 5))
            .set());
    //If you setting other scroll mode, the scrolled fade is shown from either side of display.
    viewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
}

结果如下:

enter image description here

向上滑动后

enter image description here