我有一个导航抽屉,里面有一个RecyclerView。单击RecyclerView中的项目时,我可以使用此RecyclerAdapter成功导航到我想要的活动:
public class AdapterNavigation extends RecyclerView.Adapter<AdapterNavigation.Holder> {
private List<NavigationItem> mItemList;
private Context mContext;
//this class takes a context and a list of the items you want to populate into the recycler view
public AdapterNavigation(Context context, List<NavigationItem> itemList) {
mItemList = itemList;
mContext = context;
}
@Override
public Holder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//our xml showing how one row looks
View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_view_navigation, viewGroup, false);
Holder holder = new Holder(row);
return holder;
}
@Override
public void onBindViewHolder(Holder holder, final int position) {
holder.recyclerNavigation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Intent intent;
switch (position){
//specify what activity will launch on click
case 0:
intent = new Intent(mContext, Maintenance.class);
break;
case 1:
intent = new Intent(mContext, Contact.class);
break;
default:
intent = new Intent(mContext, MainActivity.class);
break;
}
mContext.startActivity(intent);
}
});
NavigationItem item = mItemList.get(position);
holder.iconImageView.setImageResource(item.getIcon());
holder.titleTextView.setText(item.getTitle());
holder.countTextView.setText(Integer.toString(item.getCount()));
}
@Override
public int getItemCount() {
return mItemList.size();
}
public class Holder extends RecyclerView.ViewHolder {
protected ImageView iconImageView;
protected TextView titleTextView;
protected TextView countTextView;
protected RelativeLayout recyclerNavigation;
public Holder(View view) {
super(view);
iconImageView = (ImageView) view.findViewById(R.id.iconImageView);
titleTextView = (TextView) view.findViewById(R.id.titleTextView);
countTextView = (TextView) view.findViewById(R.id.countTextView);
//the whole view
recyclerNavigation = (RelativeLayout) view.findViewById(R.id.recyclerNavigation);
}
}
}
现在我要做的是在点击项目之前让导航抽屉关闭。单击Android Gmail应用程序导航菜单中的项目时的外观。
就在此之前:
mContext.startActivity(intent);
我会关闭导航抽屉。
问题是获得对该导航抽屉的引用。我正在考虑从我所拥有的上下文中获取视图,因为这就是我的全部。
有没有办法做到这一点,还是我必须更改我的一些代码?
答案 0 :(得分:1)
首先,每次绑定视图时都要创建一个clicklistener。考虑在viewholder的构造函数中将clicklistener设置为this
。您可以在侦听器中使用ViewHolder.getAdapterPosition()
。
要回答这个问题,您已经将Context
传递给适配器,为什么不将它(和视图符号)传递给导航抽屉?
答案 1 :(得分:0)
获取抽屉布局的参考,并在mContext.startActivity(intent)之前添加以下行; drawerLayout.closeDrawers();