我有一个带有按钮的Fragment,它将一个新项添加到RecycleView,并且此RecycleView在适配器上的单独类中。此RecycleView中的每个项目都有一个编辑按钮,可打开一个AlertDialog,在其中编辑该项目,完成编辑后,我希望刷新片段,单击删除按钮时,也要刷新该片段。 notifyDataSetChanged();
对我来说不起作用,也没有用,因为我不仅需要将TextView更新为RecycleView。
我尝试调用RefreshFragment()
方法,但是应用程序崩溃了。
在MyFragment.java中:
public class MyFragment extends Fragment {
private MyAdapter mAdapter;
[...]
public void RefreshFragment() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(MyFragment.this).attach(MyFragment.this).commit();
}
}
在MyAdapter.java中:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> implements Filterable{
private MyFragment my_fragment;
[...]
private void editTaskDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit product");
builder.setView(subView);
builder.create();
builder.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final int id = productList.get(position);
final String name= Name.getText().toString();
final int price= Integer.parseInt(Price.getText().toString());
mDatabase.updateProduct(id, name, price);
//REFRESH FRAGMENT HERE
my_fragment.RefreshFragment();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Canceled.", Toast.LENGTH_LONG).show();
}
});
builder.show();
}
}