在自定义TextWatcher

时间:2018-01-30 23:42:04

标签: android android-recyclerview android-adapter textwatcher

我正在尝试add/delete来自自定义RecyclerView的{​​{1}}中的项目。

这是我的自定义文本观察器

TextWatcher

它说"在这里添加一个项目到适配器列表"我想在@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

1 个答案:

答案 0 :(得分:1)

编辑:添加而不是更新 你想要的是一个连接TextWatcher和RecyclerView逻辑的接口 例如,您可以使用此界面,但可以根据需要进行修改。

interface AddPlayerInterface {
    private void addPlayer(Player player);
}

您可以在适配器中实现它 例如

    class Adapter extends RecyclerView.Adapter implements AddPlayerInterface {
        // ... your other adapter implementation codes

        @override
        private void addPlayer(Player player) {
            // here you can add the new player to the list
            list.add(player);
            notifyDataSetChanged(); // or any of the helper methods to notify adapter of change like for specific rows
        }

    }

然后通过

将您的监听器引用传递给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, listener);
}

您的textwatcher将包含要调用的接口的引用     class CustomWatcher实现TextWatcher     {        受保护的玩家;        private AddPlayerInterface listener;

   private CustomWatcher(Player player, AddPlayerInterface interface)
   {
       this.player = player;
       this.listener = interface;
   }

   @Override
   public void afterTextChanged(Editable editable)
   {
        // if you want it on after textchanged you'd call it here and you would probably create the new player instance here
       Player player = new Player();
       listener.addPlayer(player); // this would call the listener implementation on your adapter 

   }
}