在我的应用中,我需要使用一次点击并长按按钮
点击某事(调用Itemclick())并长按录制声音
并使用此代码:
send.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
{
recording =false;
t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(count>=2)
t.cancel();
count++;
}
});
}
}, 1, 1000);
break;
}
case MotionEvent.ACTION_MOVE:
{
if(count >=2&&!recording)
{
recording=true;
count=0;
Rec=new Recorder();
Rec.startRecord();
}
break;
}
case MotionEvent.ACTION_UP:
{
t.cancel();
if(!recording)
{
count=0;
Itemclick();
break;
}
recording=false;
Rec.StopRecord();
db.open();
db.insert_offline(Rec.getName(), true, false);
listItems.add(Rec.getName());
type.add("v");
adapter.notifyDataSetChanged();
db.close();
Rec=null;
break;
}
}
return false;
}
});
在这段代码中,我使用计时器来查找长按,但我想要一种简单快捷的方法来执行此操作。
您有任何想法或更好的解决方案吗?
答案 0 :(得分:4)
您可以替换计时器并使用android的内置事件侦听器进行点击和保持事件:
View.OnLongClickListener
View.OnClickListener
走这条路,您的代码将如下所示。
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//code for click event
}
});
send.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//code for hold event... which sounds like you want to begin recording here
return true; //indicate we're done listening to this touch listener
}
});
send.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_UP:
{
//stop recording voice if a long hold was detected and a recording started
return true; //indicate we're done listening to this touch listener
}
}
return false;
}
});