Sayan Sahoo Sayan Sahoo - 3 months ago 12
Android Question

I need help in my project, how can I change Intent in my RecyclerView, this is my code

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();
}


}

Answer

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);

}