- Android 中滑动删除的Item,往往是一个Item的宽度比较大,超过了手机屏幕,必须滑动才能显示完全的。
那么如何实现滑动?
- 实现滑动的前提是,当前的布局宽度超过了屏幕宽度。所以,第一个问题应该是:如何写一个布局,让其宽度超过一个屏幕?
- 这个可以直接在xml布局中完成。这里给出一个示例:
<LinearLayout android:id="@+id/main_line2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="match_parent" android:layout_height="60dp" android:background="#4433b5e5" android:gravity="center" android:padding="8dp" android:text="@string/item_left" android:textSize="24sp" /> <TextView android:layout_width="120dp" android:layout_height="60dp" android:background="#4499b5e5" android:gravity="center" android:padding="8dp" android:text="@string/item_right" android:textSize="16sp" /> </LinearLayout>
这样,就完成了一个宽度超过一个屏幕的item的布局了。
- 在完成了一个超过一个屏幕的item布局之后,接下来就是实现滑动了。实现滑动,就是重写
onTouch()
方法。重写该方法,就可以获得当前手指触摸的位移。然后让view 也做相应的位移即可。 - 示例代码如下
package com.pythoncat.lastview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnTouchListener { private int downX; private View line; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.main_line2).setOnTouchListener(this); } /** * Called when a touch event is dispatched to a view. This allows listeners to * get a chance to respond before the target view. * * @param v The view the touch event has been dispatched to. * @param event The MotionEvent object containing full information about * the event. * @return True if the listener has consumed the event, false otherwise. */ @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: downX = (int) event.getX(); break; case MotionEvent.ACTION_MOVE: int moveX = (int) event.getX(); int dx = downX - moveX; v.scrollBy(dx, 0); downX = moveX; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: default: break; } return true; } }
- 通过上面的对
onTouch()
方法的重写,就可以完成item的左右滑动了。当然,实际上,还需要做滑动边界的处理。然后是滑动释放后的状态确定,以及items上删除按钮的点击事件处理。不过这些都不重要了。
滑动删除的核心逻辑就是两点:
- 完成一个宽度超过一屏幕的Item的布局。(也可以直接在代码中实现:难度系数较大。需要很好的理解测量方法;而在xml中实现就比较简单了。多试试就出来了。)
- 重写
onTouch()
处理滑动。