gpt4 book ai didi

android - 如何在 RecyclerView Adapter 中使用 Activity 方法?

转载 作者:行者123 更新时间:2023-11-30 01:41:23 27 4
gpt4 key购买 nike

每当 Recyclerview onclick 完成时,我需要完成一个 Activity 并重新打开另一个 Activity。我已经成功地在 Recyclerview 上实现了 onclick。但是我无法在我的适配器中重新创建另一个 Activity 。

我该如何解决这个问题?

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

最佳答案

您可以在构造函数中传递对 Activity 的引用,如下所示:

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

然后,在创建适配器时在您的 Activity 中执行如下操作:

ThemeAdapter adapter = new ThemeAdapter(getContext(), this, mThemeList);

然后您可以通过调用 mActivity.someMethod() 在您的适配器中使用 Activity 方法。

免责声明:未经测试(我从未使用过 RecyclerView),但这在其他任何地方都有效。

关于android - 如何在 RecyclerView Adapter 中使用 Activity 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34465325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com