In my Android application I have used an Activity and Adapter for list view, my acquirement is need to communicate both adapter class and activity via event listener using EventBus, so that I have created two event listener classes.
My process is:
1) I have a button in the activity,the button should communicate Adapter class.
2) If I click text view (text view widgets of list view) should communicate Activity class.
By the following code it works for Adapter communicates with Activity but Activity does not communicates with adapter class. Please help me on how to communicates for both the classes?
I have posted my full sample project code:
Activity class:
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);
}
}
Adapter class:
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);
}
}
Don't create new EventBus
instance each time, use EventBus.getDefault()
.
Add to both classes method public void onEvent(Object event)