我们如何将上下文分解成碎片?

时间:2018-08-03 08:13:49

标签: android android-fragments

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);
    }

我已经使用onUpdateMapAfterUserInterection函数创建了一个接口
现在,我希望对象updateMapAfterUserInterection具有片段“ spare”的上下文来更新地图。
但它抛出“无法将上下文转换为片段” 有什么解决方法?

1 个答案:

答案 0 :(得分:1)

我为您提供解决方案。

第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.
...