Если в списке есть два элемента и я нажимаю кнопку «Удалить», почему удаляются оба элемента? - PullRequest
0 голосов
/ 30 марта 2019

У меня есть галерея изображений, в которой я перечисляю мои отредактированные изображения. Список изображений исходит от моей деятельности. Всякий раз, когда я добавляю предмет, все работает хорошо.

Например, у меня есть восемь предметов. Я хотел удалить шесть из них. Нет проблем; все работает нормально.

Но теперь я хочу удалить два других элемента по одному. Когда я нажимаю кнопку удаления на одном из них, оба они удаляются. Как я могу решить эту проблему?

Ниже приведены мой класс адаптера и активность:

public class EditedImageListAdapter extends RecyclerView.Adapter<EdittedListViewHolder> {
    private Context context;
    private ArrayList<File> mFiles;

    public EditedImageListAdapter(Context context) {
        this.context = context;
        refresh();
    }

    public void refresh() {
        String imagesFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        File downloadedImagesDir = new File(imagesFolder, "Selfie Editor");
        File[] files = downloadedImagesDir.listFiles();
        mFiles = files == null
                ? new ArrayList<File>()
                : new ArrayList<File>(Arrays.asList(files));
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public EdittedListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_editted_list, parent, false);
        return new EdittedListViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull EdittedListViewHolder holder, final int position) {
        Log.d("Files", "FileName:" + mFiles.get(position).getName());
        Glide.with(context).load(mFiles.get(position)).into(holder.listItem);

        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View v, int position, boolean isLongClick) {
                // show image
                Intent showImageIntent = new Intent(context, ResultActivity.class);
                showImageIntent.putExtra(Consts.SHOW_IMAGE, mFiles.get(position).getAbsolutePath());
                context.startActivity(showImageIntent);

            }
        });

        holder.shareImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // share image
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                sharingIntent.setType("image/*");
                sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(mFiles.get(position).getPath()));
                context.startActivity(Intent.createChooser(sharingIntent, "Share"));
            }
        });
        holder.deleteImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //delete image
                //todo when we have two items deleting both of them (except for this problem working well)
                mFiles.get(position).delete();
                EditedImageListAdapter.this.mFiles.remove(position);
                EditedImageListAdapter.this.notifyItemRemoved(position);
                EditedImageListAdapter.this.notifyItemRangeRemoved(position, getItemCount() - position);
                EditedImageListAdapter.this.notifyItemRemoved(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mFiles.size();
    }
}



public class EdittedList extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    RecyclerView recycler_list;
    EditedImageListAdapter adapter;
    private final int REQUEST_IMAGE_CAPTURE = 112;
    private final int ADOBE_FROM_GALLERY_REQUEST_CODE = 2;
    private final int ADOBE_FROM_CAPTURE_REQUEST_CODE = 3;
    private final int RESULT_GALLERY_IMAGE = 123;
    public static final int WRITE_EXTERNAL_STORAGE = 6;
    protected Uri mGalleryImageUri;
    protected Uri mCapturedImageUri;
    Uri editedImageUri;
    String fontFamily_editedList = "MarkPro-Bold.otf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editted_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorblack));
        toolbar.setTitle("Edited List");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setItemIconTintList(null);
        changeNavigationMenuItemTypeFace(navigationView);
        //recyclerview initialize
        recycler_list = findViewById(R.id.recycler_list);
        RecyclerView.LayoutManager layoutManager = new SpannableGridLayoutManager(new SpannableGridLayoutManager.GridSpanLookup() {
            @Override
            public SpannableGridLayoutManager.SpanInfo getSpanInfo(int position) {
                if (position == 0) {
                    return new SpannableGridLayoutManager.SpanInfo(2, 2);
                } else {
                    return new SpannableGridLayoutManager.SpanInfo(1, 1);
                }
            }
        }, 3, 0.8f);
        recycler_list.setLayoutManager(layoutManager);
        adapter = new EditedImageListAdapter(this);
        adapter.notifyDataSetChanged();
        recycler_list.setAdapter(adapter);
        recycler_list.setHasFixedSize(true);

        new Calligrapher(this).setFont(this, fontFamily_editedList, true);

    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.refresh();
        adapter.notifyDataSetChanged();
    }

1 Ответ

0 голосов
/ 30 марта 2019

Вы повторяете функциональность как:

mFiles.get(position).delete();
EditedImageListAdapter.this.mFiles.remove(position);

Например, есть 2 файла A, B. mFile.get (0) = A, mFile.get (1) = B,

при выполнении:

mFiles.get(position).delete();

Файлы B возвращаются назад, например mFile.get (0) = B; и А удаляется,

и с этим:

EditedImageListAdapter.this.mFiles.remove(position);

удаляет и второй тоже.

...