在我的 Android 应用程序中,我使用了 Activity 和 Adapter 作为列表视图,我需要使用 EventBus 通过事件侦听器来通信适配器类和 Activity,因此我创建了两个事件侦听器类。
我的流程是:
1)我在活动中有一个按钮,该按钮应该与适配器类通信。
2)如果我单击文本视图(列表视图的文本视图小部件)应该与 Activity 类通信。
通过以下代码,它适用于 Adapter 与 Activity 通信,但 Activity 不与适配器类通信。请帮助我了解如何在两个课程中进行交流?
我已经发布了我的完整示例项目代码:
活动类:
public class ListMobileActivity extends Activity {....};
private ListView list;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(ListMobileActivity.this);
......
list.setAdapter(adapter);
// Does not communicates with Adapter.
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EventBus.getDefault().post(new TestEvent2("test event"));
}
});
}
public void onEvent(TestFinishedEvent event) {
Log.e("TestFinishEvent ", event.test);
}
}
适配器类:
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_mobile, values);
this.context = context;
this.values = values;
EventBus.getDefault().register(this.context); // registered here.
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_mobile, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
.........
// its works, communicate with Activity
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EventBus.getDefault().post(new TestFinishedEvent("ssds"));
}
});
return rowView;
}
public void onEvent(TestEvent2 event) {
Log.e("Test event 2 ", event.test);
}
}