【问题标题】:Why the touch event on the child of my ViewGroup does'nt work?为什么我的 ViewGroup 的孩子上的触摸事件不起作用?
【发布时间】:2012-04-14 16:48:44
【问题描述】:

这是我的代码 - PadsGrid 是一个 ViewGroup - :

public class Emc_PadControllerActivity extends Activity implements OnTouchListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final PadsGrid pg = new PadsGrid(this, 8, 5, PadType.SMALL);
        for (int i=0;i<pg.getChildCount();i++){
            final PadController pc;
            pc=(View) pg.getChildAt(i);
            pc.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    pc.onTouch(arg0,arg1);
                    return true;
                }});;
        }

        setContentView(pg);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        return false;
    }
}

在这里面,我的views的onTouch事件不是叫我为什么要触摸它们,为什么?

【问题讨论】:

    标签: android view touch-event viewgroup


    【解决方案1】:

    您希望将 onTouchlistener 设置为 Emc_PadControllerActivity.this,而不是像这样使用匿名内部类:

       pc.setOnTouchListener(Emc_PadControllerActivity.this)
    

    这将在主类中调用您的 onTouch()。在这里,您可以确定点击了哪个视图并采取相应措施。

    查看我之前的question here.

    【讨论】:

    • 好的,但我希望视图直接包含 onTouchEvent。因为这种方式处理多点触控事件更快更容易!
    • 在这种情况下你应该可以pc.setOnTouchListener(pc.onTouch());... 我假设pc类有一个onTouch()方法。
    • 当然可以,但是如何将 Event 和 View 这两个参数传递给 onTocuh 方法?
    • 我已经通过在我的 PadController 中添加此方法来尝试您的解决方案: public OnTouchListener onTouch() { Log.d("PadController","Touched!");返回空值; } 但什么也没发生!
    • 我确信这是自动完成的...请参阅 [developer.android.com/reference/android/view/… 接口文档。)您的控件实现接口和方法,其余的由框架完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2017-06-11
    • 2021-10-21
    相关资源
    最近更新 更多