Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drag&Drop in Android #144

Open
soapgu opened this issue May 16, 2022 · 0 comments
Open

Drag&Drop in Android #144

soapgu opened this issue May 16, 2022 · 0 comments
Labels
Demo Demo 安卓 安卓

Comments

@soapgu
Copy link
Owner

soapgu commented May 16, 2022

  • 引言

Drag&Drop功能本身比较简单,本来不想特意写的。主要是我需要在ViewPager2里做,我们知道ViewPager2里面本来就带有横向或者纵向拖动的翻页的功能,那么我的拖拽会不会受到相互影响那?想想看以前SwipeRefreshLayout与ViewPager2 的冲突,我一下有点不确定了。所以为了保险起见我必须“验证”一下,如果搞不定要尽快换解决方案了。这个和董存瑞炸碉堡一样,不能说总攻开始了,关键的碉堡还没有拔掉。

  • Drag&Drop实现

比较奇怪的是官网并没有相关页面介绍,难道是这个功能太冷僻了,或者太简单了直接忽略了?

  • View 类的boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,Object myLocalState, int flags)

  • ClipData data:剪贴板数据,主要是发送端和接受端传输的相关数据,可以用ClipData.newXXX的函数api来创建

  • DragShadowBuilder shadowBuilder:拖拽时候的控件阴影显示效果,这里用new View.DragShadowBuilder(view)默认的就行

  • myLocalState:本地数据,这次先忽略,设null

  • flags:其中可以跨进程拖拽,我们这次也忽略,设0

  • setOnDragListener
    任何View可以通过setOnDragListener的调用来实现接收拖拽控件,通过event.getClipData()获取数据,通过event.getAction()获取具体事件类型,最后一定要返回boolean为true才能正常接收。

  • 相关代码

view.findViewById(R.id.card_one).setOnLongClickListener( v -> {
            ClipData clipData = ClipData.newPlainText("number","1");
            v.startDragAndDrop(clipData,new View.DragShadowBuilder(v),null,0);
            return true;
        } );

        view.findViewById(R.id.card_two).setOnLongClickListener( v -> {
            ClipData clipData = ClipData.newPlainText("number","2");
            v.startDragAndDrop(clipData,new View.DragShadowBuilder(v),null,0);
            return true;
        } );

        view.findViewById(R.id.view_receive).setOnDragListener((v, event) -> {
            switch (event.getAction()){
                case DragEvent.ACTION_DROP:
                    ClipData clipData = event.getClipData();
                    String text = clipData.getItemAt(0).getText().toString();
                    Toast toast = Toast.makeText(requireContext(), text, Toast.LENGTH_SHORT);
                    toast.show();
                    break;
            }
            return true;
        });

求证结果:Drag&Drop和ViewPager2 没有冲突,Drag&Drop优先级高于ViewPager2 ,大家各拖各的不影响。

@soapgu soapgu added Demo Demo 安卓 安卓 labels May 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Demo Demo 安卓 安卓
Projects
None yet
Development

No branches or pull requests

1 participant