I would like to set the same onClickListener for all items in my activity. Is it possible to do it with loop? I was trying with reflection, unfortunately without success. My code:
private void setUpOnClickListeners() {
Field[] fields = viewHolder.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
Method[] m = field.getDeclaringClass().getMethods();
for (Method method : m) {
if (method.getName().contains("setOnClickListener")) {
method.invoke(field, onClickListener);
}
}
field.setAccessible(false);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == viewHolder.mBtStartStop) {
presenter.onButtonStartStop();
} else if (v == viewHolder.mBtDetails) {
presenter.onButtonDetails();
} else if (...)
...
}
}
};
static class ViewHolder {
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
@Bind(R.id.activity_main_bt_stop)
Button mBtStartStop;
@Bind(R.id.activity_main_tv_how_many_hours)
TextView mTvHours;
@Bind(R.id.fragment_main_bt_details)
CircleButton mBtDetails;
...
...
}
It would be facilitation due to many fields in layout...
Aucun commentaire:
Enregistrer un commentaire