我想在recyclerview中长按一个项目,并有两个选项"编辑数据"and "删除数据"出现。我已经写了下面的代码,但我不明白它是如何工作的。
错误出现在View.OnLongClickListener()
错误:Class 'Anonymous class derived from OnLongClickListener' must either be declared abstract or implement abstract method 'onLongClick(View)' in 'OnLongClickListener
recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
ProgressDialog progressDialog = new ProgressDialog(view.getContext());
CharSequence[] dialogItem = {"Edit Data","Delete Data"};
builder.setTitle(sensorModels.get(position).getNome());
builder.setItems(dialogItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i){
case 0:
startActivity(new Intent(getApplicationContext(),CreateSensorActivity.class)
.putExtra("position",position));
break;
case 1:
deleteData(sensorModels.get(position).getId());
break;
}
}
});
}
});
Class 'Anonymous class derived from OnLongClickListener' must either be declared abstract or implement abstract method 'onLongClick(View)' in 'OnLongClickListener
View.OnLongClickListener
需要长按覆盖onLongClick
才能生效。您正在重写onItemClick
,这不是OnLongClickListener
的抽象方法。你必须重写onLongClick
而不是onItemClick
。
我想在回收器视图中长按一个项目
在你的代码中,看起来你在整个回收器视图recyclerView.setOnLongClickListener
上设置了一个长点击,而不是在单个项目上。
要设置recyclerview
的每个项目的长按,必须在onBindViewHolder
中设置onLongClickListener
。
@Override
public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
View view = holder.findViewById(R.id.your_view);
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
boolean onLongClick(v: View) {
//do work
return true
}
}
请不要直接在回收站视图上使用onLongClickListener。使用来自适配器的回调,并在活动中实现它。我想这一定能行。
将此代码放入适配器中,并在item长按时使用:
interface OnItemLongClickListener {
fun onItemLongClick(position: Int)
}
通过引用适配器在活动中实现OnItemLongClickListener,并在活动中重写onItemLongClick方法。