Android更新recyclerView项目

时间:2017-04-07 03:18:27

标签: android android-recyclerview

我有新数据更新recyclerview项目的简单问题,我想知道哪些代码在没有使用数据绑定的情况下工作正常,在我的代码中通过点击按钮添加新项目触发器clickOnSendCommandToRobot方法,此方法必须将新项添加到List,并且我的适配器可以知道要添加新数据并刷新RecyclerView,我不会收到任何错误,但列表大小始终为1

public class ActivityRegister extends BaseActivities {
    private RobotMessagesAdapter adapter;
    private List<RobotViewModel> model;
    private static final String TAG = "register";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_register);

        ActivityRegisterPresenter presenter = new ActivityRegisterPresenter(this);
        ActivityRegisterViewModel viewModel = new ActivityRegisterViewModel();
        binding.setViewModel(viewModel);
        binding.setPresenter(presenter);

        if (savedInstanceState == null) {
            model = new ArrayList<>();
        } else {
            model = savedInstanceState.getParcelableArrayList("model");
        }
        adapter = new RobotMessagesAdapter(this, model);
        binding.registerRobot.setAdapter(adapter);

        ...
    }
    @Override
    public void clickOnSendCommandToRobot() {
        RobotViewModel temp = new RobotViewModel();
        temp.setMessage(Math.round(Math.random()) + "");
        temp.setMessageType(SV.RobotMessageType.SENT_BY_ROBOT.ordinal());
        model.add(temp);

        Log.e(TAG, model.size() + "");

        adapter.setData(model);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList("model", (ArrayList) model);
        super.onSaveInstanceState(outState);
    }
}

适配器setData方法:

public void setData(List<RobotViewModel> data) {
    Log.e("data size ", data.size() + "");
    list.clear();
    list.addAll(data);
    notifyDataSetChanged();
}

每次点击按钮并触发clickOnSendCommandToRobot方法。 model变量清除,我没有最新添加的项目,并且适配器不会通过新添加的项目刷新列表。 logcat的:

04-08 08:29:45.342 21470-21470/com.sample.myapp E/register: 1
04-08 08:29:45.343 21470-21470/com.sample.myapp E/data size: 1
04-08 08:29:46.658 21470-21470/com.sample.myapp E/register: 1
04-08 08:29:46.658 21470-21470/com.sample.myapp E/data size: 1
04-08 08:29:47.462 21470-21470/com.sample.myapp E/register: 1
04-08 08:29:47.462 21470-21470/com.sample.myapp E/data size: 1

1 个答案:

答案 0 :(得分:2)

因为模型是对回收器视图适配器本身的引用,所以对外部模型对象所做的任何更改都会链接回适配器。在模型所在的适配器类之外,调用notifyDataSetChange there.so ^[0]{3}$删除并简单地执行^\d{3}$

adapter.setData(model);