1

This is my MainActivity, where I have used the Recylcer View, i want to change the intent when i press one of the cover pics used in the RecyclerView

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AlbumsAdapter adapter;
    private List<Album> albumList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initCollapsingToolbar();

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        albumList = new ArrayList<>();
        adapter = new AlbumsAdapter(this, albumList);


        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        prepareAlbums();

        try {
            Glide.with(this).load(R.drawable.cover2).into((ImageView) findViewById(R.id.backdrop));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Initializing collapsing toolbar
     * Will show and hide the toolbar title on scroll
     */
    private void initCollapsingToolbar() {
        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0) {
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                } else if (isShow) {
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                }
            }
        });
    }

    /**
     * Adding few albums for testing
     */
    private void prepareAlbums() {
        int[] covers = new int[]{
                R.drawable.robotics,
                R.drawable.coding,
                R.drawable.gaming,
                R.drawable.civil,
                R.drawable.electronics,
                R.drawable.onspot,
                R.drawable.album11};


        Album a = new Album("Robotics", 4, covers[0]);
        albumList.add(a);

        a = new Album("Coding", 4, covers[1]);
        albumList.add(a);

        a = new Album("Gaming", 4, covers[2]);
        albumList.add(a);

        a = new Album("Civil", 2, covers[3]);
        albumList.add(a);

        a = new Album("Electrical", 3, covers[4]);
        albumList.add(a);

        a = new Album("Miscellaneous", 6, covers[5]);
        albumList.add(a);


        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        if(view == recyclerView){
            Intent i = new Intent(getApplicationContext(), SimpleTabsActivity.class);
            startActivity(i);
        }

    }

    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }
}

This is my AdapterClass

public class AlbumsAdapter extends RecyclerView.Adapter {

private Context mContext;
private List<Album> albumList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title, count;
    public ImageView thumbnail, overflow;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        count = (TextView) view.findViewById(R.id.count);
        thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        overflow = (ImageView) view.findViewById(R.id.overflow);
    }
}


public AlbumsAdapter(Context mContext, List<Album> albumList) {
    this.mContext = mContext;
    this.albumList = albumList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.album_card, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    Album album = albumList.get(position);
    holder.title.setText(album.getName());
    holder.count.setText(album.getNumOfSongs() + " events");

    // loading album cover using Glide library
    Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);

    holder.overflow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showPopupMenu(holder.overflow);
        }
    });
}

/**
 * Showing popup menu when tapping on 3 dots
 */
private void showPopupMenu(View view) {
    // inflate menu
    PopupMenu popup = new PopupMenu(mContext, view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_album, popup.getMenu());
    popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
    popup.show();
}

/**
 * Click listener for popup menu items
 */
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {

    public MyMenuItemClickListener() {
    }

    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.action_add_favourite:
                Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_play_next:
                Toast.makeText(mContext, "Go to next", Toast.LENGTH_SHORT).show();
                return true;
            default:
        }
        return false;
    }
}

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

}

2 Answers2

0

You need to setup an onclick listener on your RecyclerView, so when a card view is clicked it will notify you which element was selected. You get that element from your adapter and pass it to the other activity through the intent. Here is a complete example code.

Passing data to another Activity when clicking on RecyclerView.

So basically you need to do these 3 things:

step 1 You need to define a layout that will be inflated inside your RecyclerView.Adapter's onCreateViewHolder callback. It will need to have this layout structure

<Some Root Layout>
    <CardView
         android:id="give it an id so you can refer it in your code">
    </CardView>
</Some Root Layout>

step 2 In your ViewHolder, get a reference for the CardView with the given id.

public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView phone;
        public CardView card;

        public ViewHolder(View itemView) {
            super(view);

            name = (TextView) itemView.findViewById(name_id);
            phone = (TextView) itemView.findViewById(phone_id);

            card = (CardView) itemView.findViewById(id of the card view);
        }
    }

step 3 In your adapter's onBindViewHolder method do this:

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        // get your object from your adapter at position

        holder.card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SecondActivity.class);
                intent.putExtra(SecondActivty.SELECTED_POSITION_KEY, position);
                startActivity(intent);
            }
        });
    }

Then in SecondActivity's onCreate method do

public static final String SELECTED_POSITION_KEY = "select_position";

private int mSelectedPosition;

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

    mSelectedPosition = getIntent().getIntExtra(SELECTED_POSITION_KEY, default_value);

}
Community
  • 1
  • 1
fuadj
  • 434
  • 4
  • 10
  • Thank you.. :) But can you tell me, what should I change in my AdapterClass, i've included that, if you can edit that, i will be very much grateful to you. – Sayan Sahoo Sep 04 '16 at 08:58
  • Sir, how can I refer different cards through the card parameter ? I mean, there is six cards in the list, i want 6 new activities for 6 cards.. how can i pass there position ? – Sayan Sahoo Sep 04 '16 at 10:00
  • getContext() , is not applicable in the Intent, it is showing error :( – Sayan Sahoo Sep 04 '16 at 10:28
  • You can use the context of MainActivity, i've updated the answer to use it. I've assumed that your adapter is defined inside MainActivity. – fuadj Sep 04 '16 at 10:30
  • It is showing MainActivity is not an enclosing class.. what to do now ? :/ – Sayan Sahoo Sep 04 '16 at 10:37
  • You can use your member variable `mContext`, i've updated the answer – fuadj Sep 04 '16 at 10:38
  • Sir, when I am doing startActivity(intent) it is showing, startAcitivity cannot be applied in AcitivityCompat – Sayan Sahoo Sep 04 '16 at 10:48
  • Hey I have done that, i forgot to put, the mContext before my startActivity – Sayan Sahoo Sep 04 '16 at 11:02
  • If the post helped you, you should accept it as an answer so others can find it helpful – fuadj Sep 04 '16 at 11:03
  • Sir, what is the default_value refers in the SecondActivity ? – Sayan Sahoo Sep 04 '16 at 11:08
  • It is part of the api for intents when you are getting a value out you should specify a default value to be used if the value doesn't exist in the intent extras. For your case you can specify -1 as the default. – fuadj Sep 04 '16 at 11:11
  • Sorry, but my app is crashing when I'm pressing any of the cardview :( what to do now ? – Sayan Sahoo Sep 04 '16 at 11:14
  • Post the exceptions' s stack trace – fuadj Sep 04 '16 at 11:16
  • java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.cardview/info.androidhive.cardview.SimpleTabsActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. – Sayan Sahoo Sep 04 '16 at 11:56
0

Inside of your onBindViewHolder in AlbumsAdapter you can set click listeners just like as you done for showPopupMenu. Just assign an id to your coverflow in your RecycleView's custom raw xml, and add this in your MyViewHolder class in adapter. Then inside onBindViewHolder you can access this view reference and set an OnClickListener to that.

holder.yourCoverFlowId.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // do your intent stuffs here
    }
});
Alex Chengalan
  • 8,211
  • 4
  • 42
  • 56