R
R
Rinat2019-09-15 10:43:11
Android
Rinat, 2019-09-15 10:43:11

Need help how to access previous snippets for deletion?

There is a fragment that displays through the RecyclerView in the photo album, when you open the photo, another fragment opens. it has a delete button. I delete the photo on the server. but when you go back to the album by clicking the back button, the photo is in place until you restart the fragment.
I still don’t quite understand how to implement probably a listener in fragment1 and send a removal request from fragment2 to the first photo by ID from . close the fragment and so that this photo is not already in the list. tell me pzhsta how to implement it correctly, where to drip?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
terminator-light, 2019-09-16
@terminator-light

there are 2 approaches here:
1) simple:
using the life cycle of fragments, you can simply reload the list in the onResume callback
minus: the entire list will be reloaded
2) create the correct
interface implemented by the activity

interface OnRemoveItemListener{
   void removeItem(int pos);
}

public class ListFragment extends Fragment {
  ...
    public void itemRemoved(int pos){
    	adapter.getData().remove(pos);
    	adapter.notifyItemRemoved(pos);
    	//это все можно делать внутри адаптера, а здесь просто вызвать его метод
    }

}

public class DetailFragment extends Fragment {
  private OnRemoveItemListener listener;
  //позиция элемента в адаптере RecyclerView
  private int position;

  public static void newInstance(int pos){
    Bundle bundle = new Bundle();
    bundle.putInt("pos", pos);
    DetailFragment f = new DetailFragment();
    f.setArguments(bundle);
    return f;
  }

  @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            listener = (OnRemoveItemListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement OnRemoveItemListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }

    public void onViewCreated(...){
    	//получаете pos из getArguments() и сохраняете в поле position
    }

//метод удаления на сервере
    public void removeItemFromApi(){
    	...
    	listener.removeItem(position);
    	...
    }

}

public class MainActivity extends AppCompatActivity implements OnRemoveItemListener{
  void removeItem(int pos){
    ListFragment f = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.detailFragment);
    f.itemRemoved(pos);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question