软件编程
位置:首页>> 软件编程>> Android编程>> Android自定义View仿探探卡片滑动效果

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

作者:pop1234o  发布时间:2023-03-18 14:54:16 

标签:Android,View,卡片滑动

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

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

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

这个自定义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交替来实现了视图的复用,这是这个控件的核心部分。

来源:https://blog.csdn.net/u012203641/article/details/78074196

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com