【问题标题】:Call a function in an activity from SimpleOnGestureListener从 SimpleOnGestureListener 调用活动中的函数
【发布时间】:2012-01-31 20:02:36
【问题描述】:

我有一个自定义画布的主要活动:

    public void onCreate(Bundle savedInstanceState) {
        ...
        CustomCanvas c = new CustomCanvas(this);
        c.requestFocus();
        cll = (LinearLayout)findViewById(R.id.CLL);
        cll.addView(c);
    }

    public void qwerty(String w) {
        ....
        TextView abc = (TextView)findViewById(R.id.TextViewabc);
        abc.setText(w);
        ....
    }

在 CustomCanvas 中,我有一个带有 SimpleOnGestureListener 的 GestureDetector。 我想从 SimpleOnGestureListener 的方法中调用 qwerty()(如 onSingleTapConfirmed)

这可能吗?如果没有,还有其他方法吗? 谢谢

....编辑.....(更多信息)

GestureDetector 是我的 CustomCanvas 中的一个对象

public class CustomCanvas extends View {

    GestureDetector gd;
    ...

    public CustomCanvas(final Context context) {
        super(context);

        gd = new GestureDetector(getContext(), new SimpleOnGestureListener() {
            ....
            //  I also use getScrollX() and getScrollY() in some of the methods here
        });
    }

    ....

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return gd.onTouchEvent(ev);
    }
}

【问题讨论】:

  • 也告诉我们GestureDetector。这是同一个班吗?

标签: android methods call


【解决方案1】:

你有两个选择。您可以在 Activity 中实现 SimpleOnGestureListener 并将其设置为 CustomCanvas,或者将 Activity 传递给 CustomCanavas,以便您可以从 CustomCanvas 类中的侦听器调用 qwerty()。

更新

public class CustomCanvas extends View {

    GestureDetector gd;
    YourActivity mYourActivity;
    ...

    public CustomCanvas(final Context context) {
        super(context);

        gd = new GestureDetector(getContext(), new SimpleOnGestureListener() {                   
              public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
                  // this implementation makes no sense 
                  if(mYourActivity != null){
                     mYourActivity.qwerty(); 
                  }    
              }    
        });
    }

    public setActivity(YourActivity activity){
         mYourActivity = activity;
    }
}

在您的 Activity 类中,您必须将 Activity 传递给 CustomCanvas。

public class YourActivity {

    public void onCreate(Bundle savedInstanceState) {
        ...
        CustomCanvas c = new CustomCanvas(this);

        // pass the activity to the canvas
        c.setActivity(this);

        c.requestFocus();
        cll = (LinearLayout)findViewById(R.id.CLL);
        cll.addView(c);
    }

    public void qwerty(String w) {
        ....
        TextView abc = (TextView)findViewById(R.id.TextViewabc);
        abc.setText(w);
        ....
    }
}

【讨论】:

  • 好的,你是不是只实现了CustomCanvas类来覆盖SimpleOnGestureListener?
  • 是的。我重写了 onScroll、onFling、onDown 和 onSingleTapConfirmed 方法
  • 嗨。非常感谢您花时间编写代码。真的很感激;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多