安卓,讓edittext隨手指移動而改變位置
我是個新手,水平有限,寫這個博文,更多是總結自己的問題,可能幫助不到別人什麼,還請見諒。
事情是老闆要求實在一個能夠隨手指移動的edittext,網上到處查詢,到處實驗,最後得出兩種可行的方案:
方案1:
在Activity的xml裡新增一個FrameLayout,裡面還有個LinearLayout,再裡面有editext,xml屬性如下:
<FrameLayout
android:id="@+id/edwordsLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="15dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/edmyWords"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="@drawable/ic_img_text_bg" />
</LinearLayout>
</FrameLayout>
Activity的程式碼裡實現onTouchEvent(MotionEvent event)方法,在這裡獲取手指實時點選的座標點,然後更新LinearLayout的所在位置:
//讓包含edittext的linearlayout隨手指的移動而改變位置
container.scrollBy(edtextX - x2, edtextY - y2);
這樣就行了。
方案2:
直接自定義一個editext類,在初始化裡讓這個editext實現OnTouchListener,通過實時監聽手指移動的座標,更新editext所在的位置:
meText.setX(event.getRawX() - editX);
meText.setY(event.getRawY() - meText.getHeight() - editY);
方案1demo地址:
http://download.csdn.net/detail/u014436704/8612517
方案2java類地址:
http://download.csdn.net/detail/u014436704/8612551