100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > android 高仿 探探卡片滑动 Android自定义View仿探探卡片滑动效果

android 高仿 探探卡片滑动 Android自定义View仿探探卡片滑动效果

时间:2020-10-25 22:34:25

相关推荐

android 高仿 探探卡片滑动 Android自定义View仿探探卡片滑动效果

Android自定义View仿探探卡片滑动这种效果网上有很多人已经讲解了实现思路,大多都用的是RecyclerView来实现的,但是我们今天来换一种实现思路,只用一个自定义的ViewGroup来搞定这个实现。

下面我们先看一下实现的效果:

这个自定义View用法也很简单,首先从github上下载或者fork这个项目,在布局中添加:

android:id="@+id/scl_layout"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

是的,没有一点废话,自定义属性可以根据自己的需求来添加。下面是代码中初始化:

public class SwipeCardActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_swipe_card);

SwipeCardLayout scl_layout=(SwipeCardLayout)findViewById(R.id.scl_layout);

Queue data = new LinkedList<>();

CardEntity cardEntity1 = new CardEntity(R.drawable.f1, "这里是美丽的湖畔");

CardEntity cardEntity2 = new CardEntity(R.drawable.f2, "这里游泳比较好");

CardEntity cardEntity3 = new CardEntity(R.drawable.f3, "向往的蓝天白云");

CardEntity cardEntity4 = new CardEntity(R.drawable.f4, "繁华的都市");

CardEntity cardEntity5 = new CardEntity(R.drawable.f5, "草原象征着理想");

data.add(cardEntity1);

data.add(cardEntity2);

data.add(cardEntity3);

data.add(cardEntity4);

data.add(cardEntity5);

scl_layout.setAdapter(new SwipeCardLayout.CardAdapter(data) {

@Override

public View bindLayout() {

return LayoutInflater.from(SwipeCardActivity.this).inflate(R.layout.card_layout,null);

}

@Override

public void bindData(CardEntity data, View convertView) {

ImageView iv_card = (ImageView)convertView.findViewById(R.id.iv_card);

TextView tv_card = (TextView) convertView.findViewById(R.id.tv_card);

iv_card.setImageResource(data.resId);

tv_card.setText(data.content);

}

});

scl_layout.setOnSwipeListener(new SwipeCardLayout.OnSwipeListener() {

@Override

public void onSwipe(int type) {

switch (type) {

case SwipeCardLayout.TYPE_RIGHT:

Toast.makeText(SwipeCardActivity.this, "right", Toast.LENGTH_SHORT).show();

break;

case SwipeCardLayout.TYPE_LEFT:

Toast.makeText(SwipeCardActivity.this, "left", Toast.LENGTH_SHORT).show();

break;

}

}

});

}

class CardEntity {

public CardEntity(int resId, String content) {

this.resId = resId;

this.content = content;

}

public int resId;

public String content;

}

}

这里必须要用一个队列来添加数据,显示的顺序就是队列的顺序。完整的代码已经上传github

接下来简单说一下实现原理,我们用两个自定义的ViewGroup来定义两个Card,一个在上,一个在下,且重写它的onTouchEvent()方法,来实现跟随手指来滑动。当我们松开手指的时候,如果Card移动的距离短,那么就执行动画将Card重置到原来位置,如果移动的距离比较远,我们就执行动画将Card移出屏幕,当动画结束后,我们将下面的Card通过View的bringToFront()方法移动到上层,而刚刚移出屏幕的那个Card就会到下层,然后再将它重置到起始位置即可。

这样我们通过两个Card交替来实现了视图的复用,这是这个控件的核心部分。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。