Android拖放– DragLinearLayout
时间:2020-02-23 14:28:53 来源:igfitidea点击:
今天,我们将学习如何使用DragLinearLayout创建android拖放功能。
使用DragLinearLayout的Android拖放
可以使用Android DragLinearLayout库代替任何LinearLayout。
为此,我们将在build.gradle文件中添加第三方库,如下所示:
compile 'com.jmedeisis:draglinearlayout:1.1.0'
上面的类库扩展了LinearLayout,自定义项是添加拖放功能。
重写onTouchEvent方法可通过编程方式检测手势运动并相应地拖放。
我们将在以后的教程中详细介绍android拖放功能。
注意:同步Gradle后,您可以在库文件夹中查看DragLinearLayout布局的完整源代码。
默认情况下,LinearLayout中的子视图不可拖动。
为此,我们将为每个ChildView调用方法setViewDraggable(View,View)。
Android拖放示例项目结构
这个android拖放项目由一个活动及其布局以及在布局中使用的可绘制图像组成。
在本教程中,我们在" styles.xml"下添加了UI小部件的属性。
Android拖放代码
下面给出了" activity_main.xml"代码:
<com.jmedeisis.draglinearlayout.DragLinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Please Drag and Drop Me Somewhere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextViewStyle"
<TextView
android:background="@android:color/holo_red_light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextViewStyle"
<TextView
android:text="This tutorial uses a third party library to drag LinearLayouts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextViewStyle"
<ImageView
android:layout_width="match_parent"
android:layout_height="120dp"
android:scaleType="centerCrop"
android:src="@drawable/img_1"
<TextView
android:text="Ever thought how dragging songs in an application playlist works!"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextViewStyle"
</com.jmedeisis.draglinearlayout.DragLinearLayout>
上面的布局由多个TextView和一个ImageView组成。
这些是可拖动布局的ChildViews。
MainActivity.java如下所示:
package com.theitroad.draggablelinearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DragLinearLayout dragLinearLayout = (DragLinearLayout) findViewById(R.id.container);
//set all children draggable except the first (the header)
for(int i = 0; i < dragLinearLayout.getChildCount(); i++){
View child = dragLinearLayout.getChildAt(i);
dragLinearLayout.setViewDraggable(child, child); //the child is its own drag handle
}
}
}
在上面的代码中,我们已将每个ChildView明确设置为可拖动的一个。
第三方库中提供的DraggableLinearLayout类包含拖放实现。
注意:该库的局限性在于它只能支持LinearLayout的垂直方向。

