我的片段中有一个回收站视图,我希望每次在广播接收器中显示推送消息时更新我的回收站视图。我的问题是当接收器调用时,它用前一个项目替换新项目但我想创建新行和上一个物品仍然存在。我搜索了很多但没有成功。这是我的片段,里面有广播接收器
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View drawer = inflater.inflate(R.layout.fragment_notif_list, container, false);
rv = (RecyclerView) drawer.findViewById(R.id.recyclerview);
rv.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(mLayoutManager);
prefs = getActivity().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
Toast.makeText(getActivity(), "Push notification is received!", Toast.LENGTH_LONG).show();
message = intent.getStringExtra("message");
title = intent.getStringExtra("title");
timestamp = intent.getStringExtra("timestamp");
Log.d("message -->", message);
Log.d("title -->", title);
Log.d("time -->", timestamp);
MessageObj messageObj = new MessageObj(message,title,timestamp);
getDataSet(messageObj.getMessage(),messageObj.getTitle(),messageObj.getDate());
}
}
};
return drawer;
}
private void getDataSet(String message,String title,String date) {
ArrayList results = new ArrayList<MessageObj>();
MessageObj obj = new MessageObj(message,title,date);
Log.d("result size :",results.size()+"");
results.add(results.size(),obj);
mAdapter = new MessageAdapter(getActivity(), results);
rv.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
答案 0 :(得分:3)
这是因为您每次收到广播时都会创建一个新的results
ArrayList和新的适配器。您需要在广播接收器范围之外创建一次数组列表和适配器。然后只需在播放时添加到数组列表中。然后在适配器上调用notifyDataSetChanged以使其更新UI。