I have defined an Activity in an Android app containing 9 button. Each button have to listen to the same event listener.
Looking at generated R class, their Ids are defined :
public static final int btn1=0x7f040001;
...
public static final int btn1=0x7f040009;
My question is: it is ok to add the listeners cycling the ID in a for loop?
for (int i= R.id.btn1; i<=R.id.btn9;i++)
{
Button button = (Button)findViewById(i);
button.setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {
...
}
});
}
Or there in some situation in which Id get reassigned by the compiler, breaking my code?
I’m using Intellij Idea environment to build the app.
I fear this would be a very bad idea in the event your R file is regenerated with non-consecutive IDs.. your better option would be to store an int array containing your IDs and loop through that
ex.