根据距离添加和删除 recyclerview 的项目

我正在开发一个应用程序,其中消息列表 (MESSAGE_RECIEVED) 应仅在特定距离(50、100、200、300 或 400 米)内可见


为此,我有一个消息 ArrayList (MESSAGE_RECIEVED)、一个带有自定义适配器的 RecyclerView 和一个包含 RecyclerView 的片段,并将其提供给我的 ArrayList。


我现在的方法如下:


删除条目(在我的适配器中):


public void removeAt(int pos) {

    mMessagesList.remove(pos);

    notifyItemRemoved(pos);

    notifyItemRangeChanged(pos, mMessagesList.size());

}

添加条目(在我的适配器中):


public void addAt(int pos, Message m){

    mMessagesList.add(pos, m);

    notifyItemInserted(pos);

}

最后我的代码确定一个项目是否太远:


ArrayList<String[]> operation = new ArrayList<>();



for (int i = 0; i < MESSAGES_RECEIVED.size(); i++){


    if(dist <= distMax){

        if(!MESSAGES_RECEIVED.get(i).isDisplayed()){

            operation.add(new String[]{"add", String.valueOf(i)});

            MESSAGES_RECEIVED.get(i).setDisplayed(true);

        }

    } else {

        operation.add(new String[]{"remove", String.valueOf(i)});

    }


}


for (String[] values : operation){

    Log.i(TAG, "recalculateDistance: " + values[0] + " " + values[1]);

    if(values[0].equals("add")){

        int pos = Integer.valueOf(values[1]);

        mRecyclerViewAdapter.addAt(pos, MESSAGES_RECEIVED.get(pos));

    } else if(values[0].equals("remove")){

        int pos = Integer.valueOf(values[1]);

        mRecyclerViewAdapter.removeAt(pos);

    }

}

此代码不起作用,因为项目已从我的消息 ArrayList 中删除。我无法删除它们,因为它们在其他地方使用(并且我有 IndexOutOfBoundsException,因为该位置超出了 ArrayList 的范围)。最重要的是,我无法删除它们,因为如果它们在定义的范围内,人们将无法看到它们。


有没有办法隐藏项目而不删除它们?我虽然复制了我的消息列表,但不知道这是否可行。


呼唤远方
浏览 139回答 1
1回答

繁花如伊

好的,我终于找到了让它工作的东西。我创建了另一个 ArrayList 并将其放置在一个静态类中(以便我可以从应用程序中的多个位置更新显示)这是我创建的方法public static void updateDisplayedMessages(){ MESSAGES_DISPLAYED.clear();&nbsp; &nbsp; getDistance(MESSAGES_RECEIVED);&nbsp; &nbsp; for(Message m : MESSAGES_RECEIVED){&nbsp; &nbsp; &nbsp; &nbsp; float dist = m.getDistance();&nbsp; &nbsp; &nbsp; &nbsp; int distMax = Integer.valueOf(VALUE_PREF_RADIUS_GEO_FENCING);&nbsp; &nbsp; &nbsp; &nbsp; if(dist < distMax){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MESSAGES_DISPLAYED.add(m);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}一旦被调用,我就notifyDataSetChanged从我的片段中调用,就是这样!可能不是最有效的实施方式,但它有效
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java