0
我需要能夠僅上下拖動包含TextView的LinearLayout。僅上下拖動LinearLayout
LinearLayout是一個RelativeLayout的子項。
這是我的佈局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/drag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#55000000"
>
<TextView
android:id="@+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="30sp"
android:textColor="#fff"
android:textStyle="bold"
android:layout_gravity="center"
android:text="The Quick Brown Fox Jumped!!"
android:padding="15dp"
/>
</LinearLayout>
</RelativeLayout>
這裏是我試過的代碼。
LinearLayout dragqueen;
dragqueen = (LinearLayout) findViewById(R.id.drag);
findViewById(R.id.drag).setOnTouchListener(new View.OnTouchListener()
{
int prevX,prevY;
@Override
public boolean onTouch(final View v,final MotionEvent event)
{
final FrameLayout.LayoutParams par=(FrameLayout.LayoutParams)v.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
par.topMargin+=(int)event.getRawY()-prevY;
prevY=(int)event.getRawY();
par.leftMargin+=(int)event.getRawX()-prevX;
prevX=(int)event.getRawX();
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_UP:
{
par.topMargin+=(int)event.getRawY()-prevY;
par.leftMargin+=(int)event.getRawX()-prevX;
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_DOWN:
{
prevX=(int)event.getRawX();
prevY=(int)event.getRawY();
par.bottomMargin=-2*v.getHeight();
par.rightMargin=-2*v.getWidth();
v.setLayoutParams(par);
return true;
}
}
return false;
}
});
我不知道如何做到這一點。我從網上的教程中複製了拖放代碼.....