0

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...

  • You don't need reflection. Are you sure you want _every_ `View` to have an `OnClickListener`? – Mike M. Apr 30 '16 at 23:37
  • Why use reflection when you can simply make a traversal method to move between the widgets of the view hierarchy and set the listener? Also, keep in mind that if you use recycling views you need to set the listener in that holder class. – user May 01 '16 at 07:44

0 Answers0