为TextView实现onTouchListener

5

我正在MainActivity中实现onTouchListener,并将一个OnTouchListener属性分配给一个Textview tv,但在运行时屏幕被按下时没有弹出消息。

MainActivity

public class MainActivity extends Activity implements View.OnTouchListener
{
    TextView tv;    
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv=(TextView)findViewById(R.id.tv);
        tv.setOnTouchListener(this);
        tv.setText(R.string.hello);
    }

    public boolean onTouch(View v,MotionEvent event)
    {
        Toast.makeText(this,"onTouch",Toast.LENGTH_LONG).show();
        return true;
    }
}

你是在模拟器上运行还是在设备上运行? - Code-Apprentice
谢谢,我正在我的安卓平板上运行它,并使用AIDE编译器来执行它。但是当我触摸屏幕时,它就不会给出任何反馈。 - Yiyangchen
@paxdiablo如果你不想被打扰,为什么还在SO上? - Christopher Mills
4个回答

3
TextView lastTV= (TextView) findViewById(R.id.lastTvValue);

lastTV.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //do stuff here
                    }

                Log.i("click text", "kakak");
                return false;
            }
        });

1

试一下,如果同意请接受

 tv.setOnTouchListener(new CustomTouchListener());

public class CustomTouchListener implements View.OnTouchListener {     
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){            
            case MotionEvent.ACTION_DOWN:
                // Action you you want on finger down.
  Toast.makeText(this,"onTouch",Toast.LENGTH_LONG).show();
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
                // Action you you want on finger up
                break;
    } 
        return false;   
    } 
}

谢谢,但是刚才我在onTouch()方法中写了一个Log.v()方法,设备似乎没有对触摸事件做出任何反应。无论如何还是谢谢你的帮助。 - Yiyangchen

0
你需要 @override onTouch 方法,尝试移除 implements onTouchListener 并重新编写正确的 import,直到你编写它才能正常工作。
@Override
public boolean onTouch(View v,MotionEvent event)
{
    Toast.makeText(this,"onTouch",Toast.LENGTH_LONG).show();
    return true;
} 

0

嗯,onTouchListener() 有时只能接收到一些用户的触摸输入。你能否将其改为onClickListener(),看看行为是否得以解决?

顺便说一下,我编译并运行了您的代码,它工作得很好。您能否让onTouch()打印一个Log.v()消息,并确保您的onTouch()被调用了吗?


谢谢,我尝试了Log.v()但是没有消息输出,然而当我尝试设置按钮并使用onClickListener()时,消息开始输出。我感觉很奇怪。 - Yiyangchen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接