如何在onvity中从onClick on RecyclerView开始活动

时间:2017-03-15 19:39:19

标签: android android-intent android-activity android-recyclerview custom-adapter

Hello Everyone当我点击RecyclerView时,我正在尝试启动活动,当我在自定义适配器中添加代码时启动它,但是当我在Activity中编写它时,只需在Log上给我一个位置。 。 所以任何帮助

这是代码OnClick in activity,这就是我尝试做的事情

@Override
    public void onItemClick(int position, View v) {
        Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
//        this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
//        Bitmap frameSelected = results.get(position).getImage();
//        Log.e("frameSelected" , frameSelected+"");
//        createImageFromBitmap(frameSelected , "frameImage");
        positionId = "" + position;
        Context context = v.getContext();
        Intent intent = new Intent(context.getApplicationContext() , FinalActivity.class);
        intent.putExtra("resultpos", "" + positionId);
        context.getApplicationContext().startActivity(intent);
        finish();
    }

这是活动

package com.abed.montage.hijabapptest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.kbeanie.imagechooser.api.ImageChooserManager;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class FrameListActivity extends AppCompatActivity implements  PhotoRecyclerViewAdapter.MyClickListener {
    private RecyclerView photoRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private List<Integer> framePhotoList ;
    List<PhotoClass> results ;
    private static String LOG_TAG = "CardViewActivity";
    String positionId ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frame_list);
        photoRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        photoRecyclerView.setHasFixedSize(true);
        int numberOfColumns = 2;
        // mLayoutManager = new LinearLayoutManager();
        photoRecyclerView.setLayoutManager(new GridLayoutManager(this , numberOfColumns));
        mAdapter = new PhotoRecyclerViewAdapter(getDataSet() , this);
        photoRecyclerView.setAdapter(mAdapter);
    }
    @Override
    protected void onResume() {
        super.onResume();
        ((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
                .MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.i(LOG_TAG, " Clicked on Item " + position);
            }
        });
    }
    private List<PhotoClass> getDataSet() {
        fillPhotoFrameList();
        results = new ArrayList<>();
        for (int index = 0; index < framePhotoList.size(); index++) {
            PhotoClass obj = new PhotoClass();
            obj.setImage(framePhotoList.get(index));
            results.add(index, obj);
        }
        return results;
    }

    private  void fillPhotoFrameList(){
        framePhotoList = new ArrayList<>();
        framePhotoList.add(R.drawable.frame_1);
        framePhotoList.add(R.drawable.frame_2);
        framePhotoList.add(R.drawable.frame_3);
        framePhotoList.add(R.drawable.frame_4);
        framePhotoList.add(R.drawable.frame_5);
        framePhotoList.add(R.drawable.frame_6);
        framePhotoList.add(R.drawable.frame_7);
        framePhotoList.add(R.drawable.frame_8);
        framePhotoList.add(R.drawable.frame_2);
        framePhotoList.add(R.drawable.frame_10);
        framePhotoList.add(R.drawable.frame_11);
        framePhotoList.add(R.drawable.frame_12);
        framePhotoList.add(R.drawable.frame_13);
        framePhotoList.add(R.drawable.frame_14);
        framePhotoList.add(R.drawable.frame_15);
        framePhotoList.add(R.drawable.frame_16);
        framePhotoList.add(R.drawable.frame_17);
        framePhotoList.add(R.drawable.frame_18);
        framePhotoList.add(R.drawable.frame_19);
        framePhotoList.add(R.drawable.frame_20);
    }

    @Override
    public void onItemClick(int position, View v) {
        Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
//        this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
//        Bitmap frameSelected = results.get(position).getImage();
//        Log.e("frameSelected" , frameSelected+"");
//        createImageFromBitmap(frameSelected , "frameImage");
        positionId = "" + position;
        Context context = v.getContext();
        Intent intent = new Intent( context  , FinalActivity.class);
        intent.putExtra("resultpos", "" + positionId);
        context.startActivity(intent);
        finish();;
    }
    public String createImageFromBitmap(Bitmap bitmap , String fileNameForSave) {
        String fileName = fileNameForSave;//no .png or .jpg needed
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            // remember close file output
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        return fileName;
    }
}

这是适配器......

package com.abed.montage.hijabapptest;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
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.ImageView;

import java.util.List;

/**
 * Created by hp15-AY on 02/27/2017.
 */

public class PhotoRecyclerViewAdapter extends RecyclerView.Adapter<PhotoRecyclerViewAdapter.DataObjectHolder> {

    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private List<PhotoClass> mDataset;
    private static MyClickListener myClickListener;
Context context;
    public static class DataObjectHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        ImageView photo;


        public DataObjectHolder(View itemView) {
            super(itemView);
            photo = (ImageView) itemView.findViewById(R.id.photo);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(), v);
//            Context context = v.getContext();
//            Intent intent = new Intent(context, FinalActivity.class);
//            context.startActivity(intent);
        }
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public PhotoRecyclerViewAdapter(List<PhotoClass> myDataset , Context context) {
        this.context = context ;
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cardview_photo, parent, false);
        view.setBackgroundResource(R.drawable.rounded_frame);
        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.photo.setImageBitmap(BitmapFactory.decodeResource(context.getResources() ,mDataset.get(position).getImage()));
    }

    public void addItem(PhotoClass dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

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

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }
}

这是班级......

public class PhotoClass {
    int id;
    int image ;

    public PhotoClass() {
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public int getId() {
        return id;
    }

    public int getImage() {
        return image;
    }

}

FinalActivity OnCreate

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "Activity Created");
        setContentView(R.layout.activity_final);

        mGlobal = (Global) getApplicationContext();

        imageViewThumbnail = (ImageView) findViewById(R.id.selectedimage);
        saveIcon = (ImageView) findViewById(R.id.imageSave);
        filterIcon = (ImageView) findViewById(R.id.editImage);
        mImageViewFrame = (ImageView) findViewById(R.id.frameimage);
//        mInterstitialAd = new InterstitialAd(this);
//        mInterstitialAd.setAdUnitId(getApplicationContext().getString(R.string.admob_intersitials));
//        mAdRequest= new AdRequest.Builder().build();
//        mInterstitialAd.loadAd(mAdRequest);
        imageViewThumbnail.setOnTouchListener(new MultiTouchListener());
        mDialog = Utils.SetProgressBar(mDialog, FinalActivity.this);
        mDialog.dismiss();

        loadImage(imageViewThumbnail, mGlobal.getPath());
        String result = getIntent().getStringExtra("resultpos");
        pos = Integer.parseInt(result);
        Log.w("Position===", "" + pos);
        String imagevalue = frames[pos];
        Log.w("imagename=====++++", "" + imagevalue);
        int resID = getResources().getIdentifier(imagevalue, "drawable", getPackageName());
        mImageViewFrame.setImageResource(resID);
        saveIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mInterstitialAd.isLoaded()) {
//                    mInterstitialAd.show();
//                }
                RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
                view.setDrawingCacheEnabled(true);
                view.buildDrawingCache();
                Bitmap bm = view.getDrawingCache();
                SaveImage(bm);
            }
        });
        filterIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
                view.setDrawingCacheEnabled(true);
                view.buildDrawingCache();
                Bitmap bm = view.getDrawingCache();
                EditImage(bm);

            }
        });}

loadImage功能:

    private void loadImage(ImageView iv, final String path) {
        if(!isAirplaneModeOn(this.getApplicationContext())) {
            Picasso.with(FinalActivity.this)
                    .load(Uri.fromFile(new File(path)))
                    .fit()
                    .centerInside()
                    .into(iv, new Callback() {
                        @Override
                        public void onSuccess() {
                            Log.i(TAG, "Picasso Success Loading Thumbnail - " + path);
                        }

                        @Override
                        public void onError() {
                            Log.i(TAG, "Picasso Error Loading Thumbnail Small - " + path);
                        }
                    });
        }
        else{
            //do something else?
        }

        File image = new File(path);
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
        engrave(bitmap);

//        bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
    }



    @SuppressWarnings("deprecation")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean isAirplaneModeOn(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return Settings.System.getInt(context.getContentResolver(),
                    Settings.System.AIRPLANE_MODE_ON, 0) != 0;
        } else {
            return Settings.Global.getInt(context.getContentResolver(),
                    Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        }
    }
}

4 个答案:

答案 0 :(得分:2)

试试这个:

onResume():您已将setOnItemClickListener附加到PhotoRecyclerViewAdapter

@Override
protected void onResume() {
    super.onResume();
    ((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
            .MyClickListener() {
        @Override
        public void onItemClick(int position, View v) {
            Log.i(LOG_TAG, " Clicked on Item " + position);
            Intent intent = new Intent(FrameListActivity.this , FinalActivity.class);
            intent.putExtra("resultpos", "" + position);
            startActivity(intent);
        }
    });
}

答案 1 :(得分:1)

使用此:

@Override
    public void onItemClick(int position, View v) {
        Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
//        this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
//        Bitmap frameSelected = results.get(position).getImage();
//        Log.e("frameSelected" , frameSelected+"");
//        createImageFromBitmap(frameSelected , "frameImage");
        positionId = "" + position;
        Context context = FrameListActivity.this;
        Intent intent = new Intent(context , FinalActivity.class);
        intent.putExtra("resultpos", "" + positionId);
        context.startActivity(intent);
        finish();
    }

希望这有帮助。

答案 2 :(得分:0)

我在setOnClickListener的{​​{1}}中使用了itemView

itemView就像所有包含该项目的东西的容器...

onBindViewHolder

这是我发现的另一个例子

我在public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> { .... .... .... @Override public void onBindViewHolder(@NonNull final MyClassViewHolder holder, int position) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); Intent intent = new Intent(context , NewActivity.class); context.startActivity(intent); } }); } .... .... } 的{​​{1}}上创建了setOnClickListener

view

答案 3 :(得分:0)

据我所知,将Name Location Total Fred Idaho 1 Dave Ohio 1 John Ohio 1 Sam Ohio 1 Cindy Virginia 1 James Virginia 1 附加到onClickListener的正确方法是在recyclerView方法中进行,如下面答案中的第一个选项所述。此方法将属性绑定到每个recyclerview项,因此onBindViewHolder也可以类似地附加。