私はFragmentクラス内にRecyclerViewを持っています。私はRecyclerViewにItemを追加したいServiceクラスを持っています。問題は、私がどうやってそれをやり遂げることができるかについて全く考えていないことです。だから私は尋ねて、誰かが私にOtto
を使うように言った。そして今、私は在庫がないので、それは機能していません。たぶん私のコードに間違ったことがあるかもしれませんが、わかりません。これは初めてのOtto
です。フラグメントとサービスのクラスでOttoを使用
これは私が私の断片クラス
public static class MyFragment extends Fragment {
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
static TheRecyclerAdapter theRecyclerAdpater;
private List<TheData> theDataList;
public static Bus bus = new Bus(ThreadEnforcer.MAIN);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.online_devices, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
theDataList = new ArrayList<>();
theRecyclerAdpater = new TheRecyclerAdapter(getActivity().getBaseContext(), theDataList);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(theRecyclerAdpater);
bus.register(this); //I already register my fragment
getActivity().startService(new Intent(getActivity(),MyService.class)); //I call the Service
return view;
}
//I already Subscribe, I am expecting to execute this Function but nothings happened
@Subscribe
public void getMessage(String s) {
TheData a = new TheData(s);
theDataList.add(a);
theRecyclerAdpater.notifyDataSetChanged();
}
}
を実装する方法であり、これは私のサービスクラスである
public class ServerHelperService extends Service {
public static Bus bus = new Bus(ThreadEnforcer.MAIN);
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
bus.post("a"); //This where I'm expecting to call the getMessage function in my fragment
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
誰もが、それは働いていない理由を考えているのか?
それは素晴らしいです。真剣に。非常に@isnotmenowありがとうございます。 –
ようこそ。私はあなたがイベントバスについて学ぶために労力を費やしてきたことを知っています。それは本当に誰かが教えることなく学習を疲れさせる。ここでは私たちの知識を共有しています。告白のように、共有は気遣うことです。良い仕事を続けてください;) –
ありがとうございました。あなたはちょうど素晴らしいです! –