我们如何将上下文转换为片段


public class TouchableWrapper extends FrameLayout {
private UpdateMapAfterUserInterection updateMapAfterUserInterection;
public TouchableWrapper(@NonNull Context context) {
super(context);
try {
updateMapAfterUserInterection = (spare) context;
// spare is fragment
// this line throws 'cannot cast context to fragment' 
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement UpdateMapAfterUserInterection");
}
}
Point touchPoint = new Point();
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
if(ev.getPointerCount()<2) {
final Point newTouchPoint = new Point();  // the new position of user's finger on screen after movement is detected
newTouchPoint.x = (int) ev.getX();
newTouchPoint.y = (int) ev.getY();
updateMapAfterUserInterection.onUpdateMapAfterUserInterection(touchPoint,newTouchPoint);
touchPoint = newTouchPoint;
}
break;
case MotionEvent.ACTION_UP:
Log.i("","up");
break;
}
return super.dispatchTouchEvent(ev);
}
// Map Activity must implement this interface
public interface UpdateMapAfterUserInterection {
public void onUpdateMapAfterUserInterection(Point touchpoint, Point newTouchpoint);
}

我已经制作了一个带有函数onUpdateMapAfterUserIntersection的接口
现在我希望对象updateMapAfteruserIntersection具有片段"备用"的上下文来更新映射
但它抛出"无法将上下文强制转换为片段"解决方法是什么?

我有一个解决方案。

步骤1:在TouchableWrapper类中添加此块

public void setUpdateMapAfterUserInterection(UpdateMapAfterUserInterection listener) {
updateMapAfterUserInterection = listener;
}

步骤2:在备用片段中,将以下块添加到onCreateView方法

TouchableWrapper view = findViewById(R.id.your_touchable_wrapper);
view.setUpdateMapAfterUserInterection(this);

更新:如果您通过代码创建TouchableWrapper视图,则

TouchableWrapper view = new TouchableWrapper(getActivity());
view.setUpdateMapAfterUserInterection(this);
// TODO: Make sure you add this custom view to root view of your activity/fragment.
...

最新更新