这篇文章主要讲解了“Android怎么实现自定义View仿探探卡片滑动效果”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Android怎么实现自定义View仿探探卡片滑动效果”吧!
Android自定义View仿探探卡片滑动这种效果网上有很多人已经讲解了实现思路,大多都用的是RecyclerView来实现的,但是我们今天来换一种实现思路,只用一个自定义的ViewGroup来搞定这个实现。
下面我们先看一下实现的效果:
这个自定义View用法也很简单,首先从github上下载或者fork这个项目,在布局中添加:
<com.liyafeng.view.swipecard.SwipeCardLayout
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<CardEntity> 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<CardEntity>(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交替来实现了视图的复用,这是这个控件的核心部分。
感谢各位的阅读,以上就是“Android怎么实现自定义View仿探探卡片滑动效果”的内容了,经过本文的学习后,相信大家对Android怎么实现自定义View仿探探卡片滑动效果这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。