我在FrameLayout中有一个ImageView,我想设置LongClickListener但它无法正常工作,我尝试设置OnTouchListener并且它的工作完美无缺,我没有任何想法为什么它不起作用但下面是我的代码代码:
public class DragImageView extends FrameLayout implements View.OnLongClickListener {
ImageView ivDrag;
public DragImageView(Context context) {
super(context);
}
public DragImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DragImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void AddImageView(View draggableObject, int x, int y, int width, int height) {
LayoutParams lpDraggableView = new LayoutParams(width, height);
lpDraggableView.gravity = Gravity.TOP;
lpDraggableView.leftMargin = x;
lpDraggableView.topMargin = y;
if(draggableObject instanceof ImageView) {
this.ivDrag = (ImageView) draggableObject;
ivDrag.setLayoutParams(lpDraggableView);
ivDrag.setClickable(true);
ivDrag.setLongClickable(true);
ivDrag.setOnLongClickListener(this);
this.addView(ivDrag);
}
}
/**
* Draggable object ontouch listener
* Handle the movement of the object when dragged and dropped
*/
private View.OnTouchListener OnTouchToDrag =new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
FrameLayout.LayoutParams dragParam = (LayoutParams) v.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
dragParam.topMargin = (int)event.getRawY() - (v.getHeight());
dragParam.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(dragParam);
break;
}
case MotionEvent.ACTION_UP:
{
dragParam.height = v.getHeight();
dragParam.width = v.getWidth();
dragParam.topMargin = (int)event.getRawY() - (v.getHeight());
dragParam.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(dragParam);
break;
}
case MotionEvent.ACTION_DOWN:
{
dragParam.height = v.getHeight();//fixed on drag and drop
dragParam.width = v.getWidth();
v.setLayoutParams(dragParam);
break;
}
}
return true;
}
};
@Override
public boolean onLongClick(View view) {
ivDrag.setOnTouchListener(OnTouchToDrag);
Toast.makeText(view.getContext(), "OnLongClick", Toast.LENGTH_SHORT).show();
return false;
}
}
答案 0 :(得分:0)
我想设置LongClickListener,但它无法正常工作
您没有收到来自OnLongClickListener
的回调,因为它没有设置侦听器。由于您的类实现了View.OnLongClickListener
并且您希望在重写的onLongClick()
方法中接收回调,因此将此类本身添加为侦听器并且它将起作用。我在构造函数中已经这样做了(根据视图的初始化,从三个中选择适当的构造函数):
public DragImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnLongClickListener(this); // <-- set this class instance as the listener
}
虽然我很惊讶你是如何使用OnTouchListener
的。您可能已明确添加了侦听器,对吧?