Reputation: 921
I need to finish an Activity & Reopen another Activity whenever a Recyclerview onclick is done. I have Implemented onclick on the Recyclerview successfully. But I can't recreate another Activity in my Adapter.
How can i solve this Issue ?
public class ThemeAdapter extends RecyclerView.Adapter<ThemeAdapter.MyVH> {
private final LayoutInflater inflater;
private List<Theme> ThemeList;
public ThemeAdapter(Context context, List<Theme> ThemeList){
inflater = LayoutInflater.from(context);
this.ThemeList = ThemeList;
}
@Override
public MyVH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.theme_card, parent, false);
MyVH holder = new MyVH(view);
return holder;
}
@Override
public void onBindViewHolder(MyVH holder, int position) {
Theme current = ThemeList.get(position);
holder.name.setText(current.Name);
holder.mCardView.setCardBackgroundColor(Color.parseColor(current.Color));
}
@Override
public int getItemCount() {
return ThemeList.size();
}
class MyVH extends RecyclerView.ViewHolder implements View.OnClickListener {
me.arulnadhan.robototextview.widget.RobotoTextView name;
CardView mCardView;
Context context;
public MyVH(View itemView) {
super(itemView);
context = itemView.getContext();
itemView.setOnClickListener(this);
name= (me.arulnadhan.robototextview.widget.RobotoTextView) itemView.findViewById(R.id.Theme);
mCardView = (CardView)itemView.findViewById(R.id.ThemeCard);
}
@Override
public void onClick(View view) {
switch (getAdapterPosition()){
case 1:
Utility.setTheme(context, 1);
ThemeActivity.recreateActivity();
}
public void recreateActivity() {
finish();
final Intent intent = IntentCompat.makeMainActivity(new ComponentName(this, MainActivity.class));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
}
Upvotes: 1
Views: 1225
Reputation: 12328
You can pass in a reference to your Activity in the constructor, like this:
(...)
private final LayoutInflater inflater;
private List<Theme> ThemeList;
private final Activity mActivity;
public ThemeAdapter(Context context, Activity mActivity, List<Theme> ThemeList){
inflater = LayoutInflater.from(context);
this.ThemeList = ThemeList;
this.mActivity = mActivity;
}
(...)
Then, in your Activity when creating the adapter, do something like this:
ThemeAdapter adapter = new ThemeAdapter(getContext(), this, mThemeList);
You can then use Activity methods in your adapter by calling mActivity.someMethod()
.
Disclaimer: not tested (I've never used RecyclerView) but this works everywhere else.
Upvotes: 1