Android 从适配器滚动到RecyclerView的底部
我知道有一种方法可以从Activities滚动到RecyclerView的底部,但是有没有任何方法可以从适配器滚动到RecyclerView的底部?我想在编辑文本被聚焦时滚动到底部 这是我的一些适配器,我想滚动到RecyclerView的底部Android 从适配器滚动到RecyclerView的底部,android,android-recyclerview,Android,Android Recyclerview,我知道有一种方法可以从Activities滚动到RecyclerView的底部,但是有没有任何方法可以从适配器滚动到RecyclerView的底部?我想在编辑文本被聚焦时滚动到底部 这是我的一些适配器,我想滚动到RecyclerView的底部 @Override public void onBindViewHolder(final ViewHolder holder, final int i) { final int position = holder.getAdapterPositio
@Override
public void onBindViewHolder(final ViewHolder holder, final int i) {
final int position = holder.getAdapterPosition();
updatePrefs();
holder.editTextListener.updatePosition(position);
holder.studentText.setHint(mDataset.get(position));
holder.studentNumber.setText(position + 1 + ".");
if (position != 0) {
holder.studentText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
holder.studentText.setHint(v.getContext().getResources()
.getString(R.string.prompt_student_name));
setDeleteListener(holder.studentDelete, position);
holder.studentText.setOnFocusChangeListener(null);
mDataset.add(v.getContext().getResources()
.getString(R.string.prompt_new_student_name));
notifyItemInserted(position + 1);
//SCROLL TO BOTTOM OF RECYCLERVIEW
}
}
});
}
//Check to make sure they're not deleting their only way of adding a new EditText
if (!holder.studentText.getHint().equals(holder.studentText.getContext().getResources()
.getString(R.string.prompt_new_student_name))) {
setDeleteListener(holder.studentDelete, position);
}
}
首先,在布局中获得
上下文的引用,最简单的方法是将其传递给构造函数:
private Context context;
public MyAdapter(ArrayList<String> data, Context context) {
this.data = data;
this.context= context;
}
实际上,您可以直接从适配器中取出RecyclerView
的引用,然后传递RecyclerView
引用,而不是上下文
。我看不出有什么不同,但通常我使用上面的方法,因为我可能需要更新其他UI元素,这样做更方便。将上下文传递给适配器,然后使用((活动)上下文)。findViewById(R.id.recyclerView)
和滚动方法在上面不起作用?这太棒了。谢谢你的提示。为了完整起见,我添加了它作为一个答案,希望它也能提供更多的可视性。通过执行:holder.itemView.getContext()可以从方法中获得“更新鲜的”Context
因此,在片段中使用RecyclerView
可以避免麻烦。您忘记了将findViewById(R.id.RecyclerView)返回的视图解析为RecyclerView。应该这样做:RecyclerView RecyclerView=(RecyclerView)((活动)this.context);
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
...
RecyclerView recyclerView = ((Activity) this.context).findViewById(R.id.recyclerView);
... use RecyclerView for your purpose
}
}