Android中的Spinner
可能不支持setOnItemLongClickListener
,因为它的用户界面性质--它本质上是一个对话框或下拉菜单.短点击后下拉菜单将关闭,因此长点击监听程序不适用于此,因此您的长点击监听程序不被触发.
If you want to add additional interaction to the spinner, you could use the normal setOnItemSelectedListener
instead.
(Examples here, and "Android - Text is Pushed to the Left in a Spinner")
You would then have to implement your own time logic if you want to simulate a long click event.
但是,由于onTouch
方法不是OnItemSelectedListener
接口的一部分,我们将需要一种不同的方法来模拟Spinner
上的长按压.正如前面提到的,它本身并不支持长点击:一种方法是创建一个定制的Spinner
类,您可以在其中自己管理touch 事件.一个非常基本的实施是:
public class LongClickSpinner extends androidx.appcompat.widget.AppCompatSpinner {
private static final long LONG_PRESS_TIME = 500; // Time in milliseconds
private long pressStartTime;
public LongClickSpinner(Context context) {
super(context);
}
public LongClickSpinner(Context context, int mode) {
super(context, mode);
}
public LongClickSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
pressStartTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
long pressDuration = System.currentTimeMillis() - pressStartTime;
if (pressDuration >= LONG_PRESS_TIME) {
// Do your long click action here
Toast.makeText(getContext(), "Long click!", Toast.LENGTH_SHORT).show();
return true;
}
break;
}
return super.onTouchEvent(event);
}
}
您可以像使用普通的Spinner
一样在您的XML布局中使用这LongClickSpinner
.当用户touch 微调按钮超过LONG_PRESS_TIME
毫秒时,您的"Long Click"操作将执行.
该解决方案仍然是一种变通办法,可能不适合所有用例.Spner不是用来处理长按事件的,它使用此自定义实现的行为可能并不完美.
如果您需要不同的交互范例来 Select 项,则可能需要考虑使用其他支持长点击的UI组件,例如ListView
或RecyclerView
.
对于ListView
或RecyclerView
,您可以拥有既支持普通点击(用于 Select 项目)又支持长点击(例如用于显示其他选项)的项目列表.然后,长点击实现将如下所示:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "long click: " + item, Toast.LENGTH_SHORT).show();
return true; // Return true to show that the event has been consumed.
}
});
使用ListView
或RecyclerView
与使用Spinner
的不同之处在于,ListView
/RecyclerView
在您的布局中始终可见,而Spinner
只有在点击后才会显示其项目.
如果您希望在具有setOnItemLongClickListener
功能的同时具有类似微调控件的行为,一种 Select 是创建一个包含ListView
或RecyclerView
的自定义对话框.这样,您就可以利用长点击监听器支持的好处来模拟微调器行为.