Search code examples
javaandroidonclickandroid-tablelayout

Loop through Android Table Layout in java activity


So I have a Table Layout with n rows and m items in each row (columns) . Each is an ImageButton and I want to add an onClick(View v) method to each one of them. Is there anyway to loop through the table and do this or do I have to hardcode it n * m times?


Solution

  • Yes, you will have to loop through the array. You need to instantiate the Buttons and set the Listeners. You will have to assign a Listener to each Button but you can respond to the the onClick() through a single method instead on making inline methods for each button which would get messy quickly.

    public class ButtonExampleActivity implements View.OnClickListener {
    
        private int[][] buttonViewIds = new int[][] {
                { R.id.button00, R.id.button01, R.id.button02 },
                { R.id.button10, R.id.button11, R.id.button12 },
                { R.id.button20...
        };
        // assuming each row is the same length you can do this
        private Button[][] buttonArray = new Button[buttonViewIds.length][buttonViewIds[0].length];
    
        @Override
        public void onCreate(Bundle b) {
            super.onCreate(b);
            setContentView(R.layout.layout);
    
            for (int i=0; i<buttonViewIds.length; i++) {
                for (int j=0; j<buttonViewIds[0].length; j++) {
                    buttonArray[i][j] = (Button) findViewById(buttonViewIds[i][j]);
                    buttonArray[i][j].setOnClickListener(this);
                }
            }
        }
    
        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.button01:
                case R.id.button02:
                case R.id.button03:
                    // do something
                    break;
                case R.id.button10:
                    // do something else
                    break;
                ...
                default:
                    Log.e("Not a handled Button: " 
                        + getResources().getResourceName(v.getId());
            }
        }
    }