【问题标题】:Where do I put the onTouchListener method in an android project?我在哪里将 onTouchListener 方法放在 android 项目中?
【发布时间】:2016-12-18 10:00:30
【问题描述】:

我已经看到很多关于如何使用onTouchListener 的答案,例如这段代码:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){

            // Do what you want
            return true;
        }
        return false;
    }
});

但我一直不清楚我应该将此代码放在我的项目中的哪个位置?到目前为止,我只编辑了我的MainActivity.java 文件,是否需要创建另一个 java 文件来容纳此代码?

【问题讨论】:

    标签: java android ontouchlistener ontouch


    【解决方案1】:

    不。小部件属性可以直接进入您的 MainActivity 代码。它应该看起来像这样:

    ImageButton imageButton = (ImageButton) findViewById(R.id.button); //instantiate the button
    imageButton.setOnTouchListener(new OnTouchListener() {...}) //set the listener
    

    另一种(不太常见的)方法是通过 XML。有关更多信息,请参阅this SO post

    【讨论】:

    • 当我这样做时,我得到错误'无法解析符号setOnTouchListener,知道为什么吗?
    • 您可能缺少导入和/或实例化不正确。查看this SO post 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2014-03-19
    • 2018-09-04
    • 1970-01-01
    • 2018-07-14
    • 2020-09-02
    • 2023-03-31
    • 2017-04-12
    相关资源
    最近更新 更多