我需要在用户在listview上保持2秒时启动添加事件。之后振动设备和显示对话框询问"添加到收藏夹?"。
我已经尝试过这个。
lv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.AXIS_PRESSURE){
long eventDuration =
android.os.SystemClock.elapsedRealtime()
- event.getDownTime();
//Put up the Yes/No message box
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert
.setTitle("Service")
.setMessage("Add to favorite?")
//.setIcon(R.drawable.chile1)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Activity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null) //Do nothing on no
.show();
}
return false;
}
上面的代码显示对话框的5次。
答案 0 :(得分:0)
首先,您需要在清单文件中允许振动:
<uses-permission android:name="android.permission.VIBRATE"/>
然后长按你可以像这里一样使用 mListView.setOnItemLongClickListener():
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> p, View v, int i, long id) {
// Do Stuff
return false;
}
});
然后在 Do Stuff 上,您可以调用 Vibrator ,然后打开要求添加到收藏夹的Dialog。 Bellow是你如何称呼振动器:
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200); // 200 miliseconds
答案 1 :(得分:0)
您可以查看下面的代码:
private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(final View view,
final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(mLongPressed,
1000);
//This is where my code for movement is initialized to get original location.
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(mLongPressed);
break;
case MotionEvent.ACTION_MOVE:
handler.removeCallbacks(mLongPressed);
//Code for movement here. This may include using a window manager to update the view
break;
}
return true; }
};
//Put this into the class
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
//TODO :show dialog when hold 1s.
// can you set time show dialog handler.postDelayed(mLongPressed, 1000);
}
};
设置OnTouch: 的 lv.setOnTouchListener(onTouchListener); 强>