How to control elements within an item in an android listview?

1

I have a list view that contains items, each item contains a seekBar. How do I control this seekbar? make it change the value when it is moved and get its current value? As this seekbar is not part of the current view, I can not co-control it ...

    
asked by anonymous 23.09.2018 / 03:56

1 answer

0

You must set the listener on the adapter and call it to retrieve the events through an interface, then a code snippet of an application of mine, the logic is the same

GalleryAdapter

In the case of ListView you should create a custom adapter with the BaseAdapter , but in my case I I use the RecyclerView adapter:

package com.samuelives.videoplayer.util;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.samuelives.videoplayer.R;

import java.util.ArrayList;

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.GalleryHolder> {

    private ArrayList<GalleryItem>mItems;
    private Context mContext;
    private LayoutInflater mInflater;
    private RequestOptions mThumbOptions;
    private GalleryListener mGalleryListener;

    public GalleryAdapter(@NonNull Context context, ArrayList<GalleryItem>items){
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int optionW = (int)(context.getResources().getDimension(R.dimen.rowVideoThumbnailW) / context.getResources().getDisplayMetrics().density);
        int optionH = (int)(context.getResources().getDimension(R.dimen.rowVideoThumbnailH) / context.getResources().getDisplayMetrics().density);
        this.mThumbOptions = new RequestOptions().override(optionW, optionH).centerCrop();
        this.mContext = context;
        this.mItems = items;
    }

    public ArrayList<GalleryItem> getData(){
        return mItems;
    }

    public void addItem(GalleryItem item, int position){
        mItems.add(item);
        notifyItemInserted(position);
        notifyItemRangeChanged(position, mItems.size());
    }

    public void removeItem(int position){
        mItems.remove(position);
        mItems.trimToSize();
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mItems.size());
    }

    public void setGalleryListener(GalleryListener listener){
        this.mGalleryListener = listener;
    }

    @NonNull
    @Override
    public GalleryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = mInflater.inflate(R.layout.gallery_list, parent, false);
        return new GalleryHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull GalleryHolder holder, int position) {

        GalleryItem item = mItems.get(position);

        holder.title.setText(item.getVideoTitle());
        Glide.with(mContext).load(item.getVideoFile()).apply(mThumbOptions).into(holder.thumbnail);
    }

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

    public class GalleryHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail = null;
        TextView title = null;
        private ImageButton popupButton;

        public GalleryHolder(View itemView) {
            super(itemView);

            thumbnail = (ImageView)itemView.findViewById(R.id.rowVideoThumbnail);
            title = (TextView)itemView.findViewById(R.id.rowVideoTitle);
            popupButton = (ImageButton) itemView.findViewById(R.id.rowBtnPopup);
            popupButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGalleryListener.onItemContextClick(popupButton, getAdapterPosition());
                }
            });

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            mGalleryListener.onItemClick(v, getAdapterPosition());
        }
    }

    public interface GalleryListener{

        void onItemClick(View v, int position);

        //Nesta linha eu defino um listener para cada botão de cada item do meu recycler view, no se caso você deve criar uma inteface para os listener da sua SeekBar
        void onItemContextClick(ImageButton btn, int position);

    }
}

GalleryFragment

This fragment that has the list in question, here I treat all listeners

package com.samuelives.videoplayer.fragments;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.samuelives.videoplayer.R;
import com.samuelives.videoplayer.player.VPlayer;
import com.samuelives.videoplayer.util.GalleryAdapter;
import com.samuelives.videoplayer.util.GalleryItem;
import com.samuelives.videoplayer.util.StorageHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

public class GalleryFragment extends Fragment {

    private RecyclerView rvGallery = null;
    private TextView tvEmpty = null;
    private GalleryAdapter mAdapter = null;
    private ArrayList<File> mVideos = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Setup RecycleView
        rvGallery.setHasFixedSize(true);

        LinearLayoutManager llManager = new LinearLayoutManager(getActivity());
        llManager.setOrientation(LinearLayoutManager.VERTICAL);

        rvGallery.setLayoutManager(llManager);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

        File storageLocation = null;

        try{

            if(prefs.getBoolean("pref_key_is_storage_in_sdcard", true)){
                storageLocation = StorageHelper.getStorage(getActivity());
                if(!storageLocation.exists()){
                    storageLocation.mkdirs();
                }
            }else{
                storageLocation = StorageHelper.getInternalStorage(getActivity());
                if(!storageLocation.exists()){
                    storageLocation.mkdirs();
                }
            }

            mVideos = new ArrayList<>(Arrays.asList(storageLocation.listFiles()));
        }catch (NullPointerException e){
            Log.e("Gallery", "Could not list files: " + e.getMessage());
        }

        ArrayList<GalleryItem> items = new ArrayList<>();

        if(mVideos != null){

            GalleryItem galleryItems[] = new GalleryItem[mVideos.size()];
            for(int i = 0; i < mVideos.size(); i++){
                galleryItems[i] = new GalleryItem(mVideos.get(i).getName(), mVideos.get(i));
                items.add(galleryItems[i]);
            }

        }

        mAdapter = new GalleryAdapter(getActivity(), items);
        mAdapter.setGalleryListener(mGalleryListener);

        if(items.isEmpty()){
            rvGallery.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        }else{
            rvGallery.setAdapter(mAdapter);
            rvGallery.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_gallery, container, false);

        rvGallery = (RecyclerView)layout.findViewById(R.id.rvGallery);
        tvEmpty = (TextView)layout.findViewById(R.id.rvGallEmptyView);

        return layout;
    }

    //Listener definido em GalleryAdapter, aqui eu trato os respectivos eventos com base das suas respectivas posicoes na lista
    private GalleryAdapter.GalleryListener mGalleryListener = new GalleryAdapter.GalleryListener() {

        @Override
        public void onItemClick(View v, int position) {

            Log.d("Gallery Listener", "Position: " + position + " Title: " + mVideos.get(position).getName());

            Intent itPlayer = new Intent(getActivity(), VPlayer.class);
            itPlayer.putExtra("videoSrc", mVideos.get(position).getPath());
            itPlayer.putExtra("videoTitle", mVideos.get(position).getName());
            itPlayer.putExtra("isOnline", false);
            itPlayer.putExtra("videoW", getWidth(mVideos.get(position).getPath()));
            itPlayer.putExtra("videoH", getHeight(mVideos.get(position).getPath()));
            startActivity(itPlayer);
        }

        @Override
        public void onItemContextClick(ImageButton btn, final int position) {

            PopupMenu contextMenu = new PopupMenu(getActivity(), btn);
            contextMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {

                    switch(item.getItemId()){

                        case R.id.deleteVideo:

                            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setMessage(R.string.galleryDeleteDialogTitle);
                            builder.setPositiveButton(R.string.galleryDeleteDialogYesButton, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    if(!mVideos.get(position).delete()){
                                        Toast.makeText(getActivity(), R.string.galleryDeleteToastError, Toast.LENGTH_LONG).show();
                                    }else{
                                        mVideos.remove(position);
                                        mVideos.trimToSize();
                                        mAdapter.removeItem(position);
                                        if(mVideos.size() == 0){
                                            rvGallery.setVisibility(View.GONE);
                                            tvEmpty.setVisibility(View.VISIBLE);
                                        }
                                    }

                                }
                            });
                            builder.setNegativeButton(R.string.galleryDeleteDialogNoButton, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.show();

                            break;

                        case R.id.infoVideo:

                            FileInfoFragment fileInfoFragment = new FileInfoFragment();
                            Bundle args = new Bundle();
                            args.putString("videoPath", mVideos.get(position).getAbsolutePath());
                            args.putString("videoName", mVideos.get(position).getName());
                            fileInfoFragment.setArguments(args);
                            fileInfoFragment.show(getActivity().getSupportFragmentManager(), fileInfoFragment.getTag());

                            break;

                        case R.id.shareVideo:

                            Intent itShare = new Intent();
                            itShare.setAction(Intent.ACTION_SEND);
                            itShare.setType("video/*");
                            itShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mVideos.get(position)));
                            startActivity(itShare);

                            break;

                    }

                    return false;
                }
            });
            MenuInflater inflater = contextMenu.getMenuInflater();
            inflater.inflate(R.menu.menu_popup_gallery, contextMenu.getMenu());
            contextMenu.show();

        }
    };

    private int getWidth(String url){

        int width = 0;

        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(url);
            width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
            retriever.release();
        }catch (NumberFormatException | NullPointerException e){
            Log.e("Get Video Width", e.getMessage());
        }

        return width;
    }

    private int getHeight(String url){

        int height = 0;

        try {

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(url);
            height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
            retriever.release();
        }catch (NumberFormatException | NullPointerException e){
            Log.e("Get Video Height", e.getMessage());
        }

        return height;
    }

}
    
23.09.2018 / 16:34