不确定解决此问题的最佳方法。我有一个RecyclerView
代表数据库中的记录列表(我正在使用SugarOrm;但是,这对问题来说无关紧要)。
我想表示数据更改,并允许用户通过onClick
和onLongClick
事件执行CRUD功能。例如,如果用户长按RecyclerView
中的视图,我希望他们可以选择删除记录。问题是仅使用ViewHolder
在视图中很容易反映更新;但是,删除记录并不容易。 ViewHolder
作为静态内部类,无法访问RecyclerView
本身来修改适配器数据或通知数据已更改。
一个选择是我可以使内部ViewHolder
类不是静态;但是,我应该关注潜在的内存泄漏吗?感觉这将是最简单的解决方案;但是,我应该使用完全不同的模式(例如让另一个类成为onClickListener
)吗?
我想保持我的代码可读性,并尽可能地作为标准练习;但是,如果它违反最佳做法或效率低下,则不会。
为清晰起见,请参见下文。
要在ViewHolder中显示的SugarOrm模型类:
public class SomeModel extends SugarRecord{
@Column(name="Name")
public String name;
@Column(name="AddedDate")
public Date addedDate = new Date();
}
RecyclerViewAdapter和ViewHolder :
public class SomeModelRecyclerViewAdapter
extends RecyclerView.Adapter<SomeModelRecyclerViewAdapter.ViewHolder>{
private List<SomeModel> data;
public SomeModelRecyclerViewAdapter(List<SomeModel> data) {
this.data = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.model_item, parent, false);
ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(holder);
view.setOnLongClickListener(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.someModel = data.get(position);
holder.bindData();
}
@Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private static final SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SomeModel someModel;
TextView modelNameLabel;
TextView modelDateLabel;
public SomeModel getSomeModel() {
return someModel;
}
public void setSomeModel(SomeModel someModel) {
this.someModel = someModel;
}
public ViewHolder(View itemView) {
super(itemView);
}
public void bindData() {
modelNameLabel = (TextView) itemView.findViewById(R.id.modelNameLabel);
modelDateLabel = (TextView) itemView.findViewById(R.id.modelDateLabel);
modelNameLabel.setText(someModel.name);
modelDateLabel.setText(dateFormat.format(someModel.addedDate));
}
@Override
public void onClick(View v) {
someModel.addedDate = new Date();
someModel.save();
bindData();
}
@Override
public boolean onLongClick(View v) {
someModel.delete();
return true;
}
}
}
活动:
public class MainActivity extends AppCompatActivity {
EditText modelName;
Button addModelButton;
RecyclerView modelList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelName = (EditText) findViewById(R.id.modelName);
addModelButton = (Button) findViewById(R.id.addModelButton);
modelList = (RecyclerView) findViewById(R.id.modelList);
addModelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SomeModel newRecord = new SomeModel();
newRecord.name = modelName.getText().toString();
newRecord.save();
setupRecyclerView();
}
});
setupRecyclerView();
}
private void setupRecyclerView() {
List<SomeModel> allModels = SomeModel.listAll(SomeModel.class);
SomeModelRecyclerViewAdapter adapter = new SomeModelRecyclerViewAdapter(allModels);
modelList.setHasFixedSize(true);
modelList.setLayoutManager(new LinearLayoutManager(this));
modelList.setAdapter(adapter);
}
}
活动布局(activity_main.xml
):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.aaronmbond.recyclerviewdilemaexample.MainActivity">
<EditText
android:id="@+id/modelName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
/>
<Button
android:id="@+id/addModelButton"
android:layout_alignParentStart="true"
android:layout_below="@id/modelName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/addModelButtonText"
/>
<android.support.v7.widget.RecyclerView
android:id="@+id/modelList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/addModelButton"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
RecyclerView项目布局(model_item.xml
):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/modelNameLabel"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/modelDateLabel"
android:layout_alignParentStart="true"
android:layout_below="@id/modelNameLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
答案 0 :(得分:2)
The ViewHolder, as a static inner class, doesn't have access to the RecyclerView itself to to modify the adapter data or notify that the data changed.
因此,处理此问题的方法是定义一个接口,该接口封装了viewholder中需要在RecyclerView上触发某些内容的所有操作。我的代码中的示例接口定义 -
/**
* Parent fragment or activity to implement this interface to listen to item deletes.
* Item deletes effect the state of the parent
*/
public interface OnItemModifiedListener {
void itemDeleted(Cart.CartItem item);
void itemQuantityChanged(Cart.CartItem item, int newQuantity);
void itemRemovedAll();
}
父片段或Activity实现此接口并将其作为其构造函数的一部分传递给Adapter。我的代码再次使用示例构造函数 -
public SimpleItemRecyclerViewAdapter(Context context, List<Cart.CartItem> items, OnItemModifiedListener l) {
//this variable is declared as a adapter state variable
mItemModifiedListener = l;
}
现在,当您在视图中发生某个操作(特别是单击)时,请在此界面上调用相应的方法。再次从我的代码中取样,我在删除行时调用此接口 -
holder.mDeleteView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//show an alert to user to confirm before remving the item from cart
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
//alertDialog.setTitle("Alert");
alertDialog.setMessage(getString(R.string.alert_remove_item_from_cart_text));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mValues.remove(holder.mItem);
if(null != mItemModifiedListener)mItemModifiedListener.itemDeleted(holder.mItem);
notifyItemRemoved(position);
//notifyDataSetChanged();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(android.R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
以下链接也是一个很好的阅读 - https://antonioleiva.com/recyclerview-listener/
希望这会有所帮助......