按项目时在Toast适配器片段中显示消息

时间:2017-04-13 02:25:06

标签: java android android-fragments gridview android-recyclerview

我试图通过按回收物品来显示碎片中的吐司,但我看不到它

注意:附加到我班级的日志中没有错误

这是我的片段

public class FotoFragment extends Fragment 
{
    private Cursor cursor;
    private int columnIndex;
    private static final String TAG = "RecyclerViewExample";

    private List<DataPictures> mediaList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private MediaRVAdapter adapter;
    String type = "";

    public FotoFragment() {
    }

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

        type = "images";
        new MediaAsyncTask().execute(type);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        return view;
    }

    public class MediaAsyncTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            String type = params[0];
            try {
                mediaList = new ArrayList<>();
                if (type.equalsIgnoreCase("images")) {
                    result = 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = 0;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result == 1) {
                adapter = new MediaRVAdapter(getActivity(), mediaList);
                mRecyclerView.setAdapter(adapter);
                mRecyclerView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "Click pressed",Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Log.e(TAG, "Failed to show list");
            }
        }
    }
}

这是我的适配器

public class MediaRVAdapter extends RecyclerView.Adapter<MediaListRowHolder> {
    private List<DataPictures> itemList;

    private Context mContext;

    public MediaRVAdapter(Context context, List<DataPictures> itemList) {
        this.itemList = itemList;
        this.mContext = context;
    }

    @Override
    public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
        MediaListRowHolder mh = new MediaListRowHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
        try{
            DataPictures item = itemList.get(i);

            Uri uri = Uri.fromFile(new File(item.getFilePath()));
            if(item.getFileType().equalsIgnoreCase("video")) {
                Bitmap bmThumbnail = ThumbnailUtils.
                        extractThumbnail(ThumbnailUtils.createVideoThumbnail(item.getFilePath(),
                                MediaStore.Video.Thumbnails.FULL_SCREEN_KIND), 90, 60);
                if(bmThumbnail != null) {
                    mediaListRowHolder.thumbnail.setImageBitmap(bmThumbnail);
                }
            } else if (item.getFileType().equalsIgnoreCase("audio")) {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(item.getFilePath());
                try{
                    if (mmr != null) {
                        byte[] art = mmr.getEmbeddedPicture();
                        Bitmap bmp = BitmapFactory.decodeByteArray(art,0,art.length);
                        if(bmp != null) {
                            bmp= ThumbnailUtils.extractThumbnail(bmp,90,60);
                            mediaListRowHolder.thumbnail.setImageBitmap(bmp);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                Picasso.with(mContext).load(uri)
                        .error(R.drawable.logo_slogan)
                        .placeholder(R.drawable.logo_slogan)
                        .centerCrop()
                        .resize(90, 60)
                        .into(mediaListRowHolder.thumbnail);

            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }
}

适配器类适配器

public class MediaListRowHolder extends RecyclerView.ViewHolder {
    protected ImageView thumbnail;
    protected TextView title;

    public MediaListRowHolder(View view) {
        super(view);
        this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        this.title = (TextView) view.findViewById(R.id.title);
    }
}

溶液:

public class MediaListRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail;
protected TextView title;


public MediaListRowHolder(View view) {
    super(view);
    this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
    this.title = (TextView) view.findViewById(R.id.title);
    view.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Toast.makeText(v.getContext(), "position = " + getPosition(), Toast.LENGTH_SHORT).show();

}

}

1 个答案:

答案 0 :(得分:0)

我认为你可以这样做,例如以下代码:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Author:Administrator on 2016/9/2 0002 20:37
 * Contact:289168296@qq.com
 */
public abstract class OnItemSelectedListener implements RecyclerView.OnItemTouchListener{

  private final GestureDetector mGestureDetector;

  public OnItemSelectedListener(Context context){
   mGestureDetector = new GestureDetector(context,
       new GestureDetector.SimpleOnGestureListener(){

         @Override public boolean onSingleTapUp(MotionEvent e) {
           return true;
         }
       });
  }

  public abstract void onItemSelected(RecyclerView.ViewHolder holder, int position);

  @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
    if (mGestureDetector.onTouchEvent(e)) {
      View touchedView = rv.findChildViewUnder(e.getX(), e.getY());
      onItemSelected(rv.findContainingViewHolder(touchedView),
          rv.getChildAdapterPosition(touchedView));
    }
    return false;
  }

  @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    throw new UnsupportedOperationException("Not implemented");
  }
}

然后到RecycleView注册事件,可以处理事件:

private RecyclerView grid;

  grid.setAdapter(new PhotoAdapter(this, relevantPhotos));
    grid.addOnItemTouchListener(new OnItemSelectedListener(MainActivity.this) {
      @Override public void onItemSelected(RecyclerView.ViewHolder holder, int position) {
        if (!(holder instanceof PhotoViewHolder)) {
          return;
        }
        PhotoItemBinding binding = ((PhotoViewHolder) holder).getBinding();
        final Intent intent = getDetailActivityStartIntent(MainActivity.this, relevantPhotos, position, binding);
        final ActivityOptions activityOptions = getActivityOptions(binding);
        MainActivity.this.startActivityForResult(intent, IntentUtil.REQUEST_CODE,
            activityOptions.toBundle());
      }
    });

PhotoAdapter.java:

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.googlesamples.unsplash.R;
import com.googlesamples.unsplash.data.model.Photo;
import com.googlesamples.unsplash.databinding.PhotoItemBinding;
import com.googlesamples.unsplash.ui.ImageSize;
import java.util.ArrayList;

public class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {

    private final ArrayList<Photo> photos;
    private final int requestedPhotoWidth;
    private final LayoutInflater layoutInflater;

    public PhotoAdapter(@NonNull Context context, @NonNull ArrayList<Photo> photos) {
        this.photos = photos;
        requestedPhotoWidth = context.getResources().getDisplayMetrics().widthPixels;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public PhotoViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        return new PhotoViewHolder((PhotoItemBinding) DataBindingUtil.inflate(layoutInflater,
                R.layout.photo_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final PhotoViewHolder holder, final int position) {
        PhotoItemBinding binding = holder.getBinding();
        Photo data = photos.get(position);
        binding.setData(data);
        binding.executePendingBindings();
        Glide.with(layoutInflater.getContext())
                .load(holder.getBinding().getData().getPhotoUrl(requestedPhotoWidth))
                .placeholder(R.color.placeholder)
                .override(ImageSize.NORMAL[0], ImageSize.NORMAL[1])
                .into(holder.getBinding().photo);
    }

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

    @Override
    public long getItemId(int position) {
        return photos.get(position).id;
    }
}