Swipe effect like inshorts news app

不羁岁月 提交于 2020-01-01 03:39:10

问题


link check this news app, i want to develop like this.

i want swipe up/down side effect..

i tried this code,but not correctly swiping as i want. in this code when i swipe up/down,only the text is changing not a layout.

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

回答1:


This will work like inshorts app

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



回答2:


I got the solution for your problem as inshorts app using vertical view pager. I am sharing some code that can serve your purpose.

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

As you can see the class above uses the DefaultTransformer class for transformation which implement ViewPager.PageTransformer for custom animation this class code is given below

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

and my activity code is like this

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

The layout named activity_swipe_layout is like this

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

<gmaillogindemo.com.irk.transforms.VerticalViewPager
    android:id="@+id/vertical_viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and the result is looking like this:

after swipe up



来源:https://stackoverflow.com/questions/34065003/swipe-effect-like-inshorts-news-app

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