从适配器滚动到RecyclerView的底部

时间:2016-03-23 00:02:02

标签: android android-recyclerview

我知道有一种方法可以从活动中滚动到RecyclerView的底部,但是有什么方法可以从适配器滚动到RecyclerView的底部吗?我想在关注EditText时滚动到底部。

以下是我的一些适配器,我想滚动到RecyclerView的底部。

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

1 个答案:

答案 0 :(得分:1)

首先,您可以获得布局中Context的引用,最简单的方法是将其传递给构造函数:

private Context context;

public MyAdapter(ArrayList<String> data, Context context) {
    this.data = data;
    this.context= context;
}

在回调中,只需从之前传递的RecyclerView获取对Context的引用

public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus) {
        ...
        RecyclerView recyclerView = ((Activity) this.context).findViewById(R.id.recyclerView);
        ... use RecyclerView for your purpose  
    }
}

实际上,您可以直接从适配器中获取RecyclerView的引用,然后传递RecyclerView引用而不是Context。我没有看到任何区别,但通常我使用上述方法,因为我可能需要更新其他UI元素,这样做更方便。