我正在 Android 上试用 Otto,我正在尝试从我的 Fragment 向 Activity 发回一条消息。这是我的代码的基础知识:
我的巴士供应商:
public final class BusProvider {
private static final Bus mInstance = new Bus();
private BusProvider() {}
public static Bus getBusProviderInstance() {
return mInstance;
}
}
我的活动有以下代码:
public class MyActivity
extends BaseActivity {
// ....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BusProvider.getBusProviderInstance().register(this);
// ....
}
@OnClick(R.id.profile_image)
public void onImageClicked() {
// ...
MyFragment fragment = MyFragment.newInstance(choices);
fragment.show(getFragmentManager(), "myChoices");
}
@Subscribe
public void onButtonChoicePicked(MyFragment.ChoicePickedEvent event) {
Toast.makeText(this, "reaching here", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
BusProvider.getBusProviderInstance().unregister(this);
}
// ...
}
这些是我的片段中的重要代码位:
public class MyFragment
extends BaseDialogFragment {
// ...
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_choices,
container,
false);
setupDialogButtons(inflater, layout);
return layout;
}
private void setupDialogButtons(LayoutInflater inflater, LinearLayout parentView) {
ChoiceButtonViewHolder holder;
holder = new ChoiceButtonViewHolder(inflater, parentView);
holder.populateContent("First Choice", 1);
parentView.addView(holder.mChoiceTextView);
}
class ChoiceButtonViewHolder {
@InjectView(R.id.item_dialog_choice_desc) TextView mChoiceTextView;
private int mPosition;
ChoiceButtonViewHolder(LayoutInflater inflater, ViewGroup container) {
TextView mChoiceTextView = (TextView) inflater.inflate(R.layout.item_dialog_choice, container, false);
ButterKnife.inject(this, mChoiceTextView);
}
public void populateContent(String choiceDesc, int position) {
mChoiceTextView.setText(choiceDesc);
mPosition = position;
}
@OnClick(R.id.item_dialog_choice_desc)
public void onChoiceClicked() {
MyFragment.this.mDialog.dismiss();
BusProvider.getBusProviderInstance().post(new ChoicePickedEvent(1));
}
}
public static class ChoicePickedEvent {
public int mPositionClicked;
ChoicePickedEvent(int position) {
mPositionClicked = position;
}
}
}
我没有收到任何错误。但是当我从片段中单击我的按钮时,不会调用 onButtonChoicePicked 事件。
难道我做错了什么?我误解了奥托的工作原理吗?是不是 ButterKnife 和 Otto 的奇怪组合使它不起作用?