【发布时间】:2018-01-30 23:42:03
【问题描述】:
我正在尝试从自定义 TextWatcher 中 add/delete RecyclerView 中的一个项目。
这是我的自定义文本观察器的一部分
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the position and size from edit text
int position = (int) editText.getTag(R.string.position);
int size = (int) editText.getTag(R.string.listSize);
//if the character count equals 1
if (count == 1){
//check if the current position is proven to be the last item in the list
if (position + 1 == size){
//add an item to the list here
}
}
}
上面写着“在此处向适配器列表添加一个项目”我想向我的recyclerview 添加一个项目并更新适配器。
我很确定没有办法轻易做到这一点。我是否需要使用Singleton design pattern 进行设置,或者有什么方法可以在我的MainActivity 上创建一个自定义侦听器,当我想添加一个项目时调用它?
我也在使用自定义适配器,如果有人需要,我可以发布。
**使用我的自定义适配器更新
public class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder>{
private List<Players> playerList;
public PlayerAdapter(List<Players> list) {
playerList = list;
}
/* ViewHolder for each item */
public class PlayerHolder extends RecyclerView.ViewHolder {
EditText playerName;
PlayerHolder(View itemView) {
super(itemView);
Log.e("Holder","setview");
playerName = itemView.findViewById(R.id.name);
MyTextWatcher textWatcher = new MyTextWatcher(playerName);
playerName.addTextChangedListener(textWatcher);
}
}
@Override
public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.new_player_item_layout, parent, false);
return new PlayerHolder(itemView);
}
@Override
public void onBindViewHolder(PlayerHolder holder, int position) {
Players playerItem = playerList.get(position);
//Sets Text
//holder.playerName.setText(playerItem.getName());
holder.playerName.setTag(R.string.listSize, playerList.size());
holder.playerName.setTag(R.string.position, position);
}
@Override
public int getItemCount() {
return playerList.size();
}
public void updateList(List<Players> newList){
playerList = newList;
notifyDataSetChanged();
}
}
【问题讨论】:
-
您的 customTextWatcher 和 CustomAdapter 是否在同一个类中实例化?即活动?
-
Adapter在MainActivity中实例化,自定义TextWatcher在我的Adapter中实例化。适配器有一个扩展 recyclerview.viewholder 的视图持有者,并在我的 PlayerHolder(View itemView) 中实例化我的 TextWatcher。我将在上面添加我的适配器
-
是的,现在是。
标签: android android-recyclerview android-adapter textwatcher