Search code examples
androidsqltableviewclickable

TableView from SQL with OnClickListener


I've been searching and found some Questions, but not the one I want to ask. First, second and not so for my theme third one provided me some help, but not at all.

I want to make a tableview which is populated from database with dbquery. Every tablerow contains three textviews, first and last column are 4-digit numbers and last one is a String around 30 letters.

All of that I can manage somehow. The problem is that I want to make every row a clickable element. I have a dream about using an cursorAdapter first to populate and then for OnClickListener but as far as I know there is nothing like this for tableviews. And gridView is not a solution for me, because I need to have first and last column much more narrow than the middle one. At least I didn't find the way to do this in gridview.

Do You have any idea? If You need some additional info, please ask me and I'll do my best.

Thanks


Solution

  • /**
     * Call once per row.
     * 
     * @param data
     *            Text containing data for each cell.
     * @param rowId
     *            unique id for OnClickListener
     */
    public void addRow(String[] data, int[] rowId) {
        for (int i = 0; i < data.length; i++) {
            TextView tv = getTextViewAndMakeThemPretty(data[i]);
            tv.setId(rowId[i]);
            tv.setFocusable(false);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /**
                     * Do your stuff here.
                     */
    
                }
            });
            this.addView(tv);
            /**
             * Adds the TextView to Row as Cell
             */
        }
    }
    

    You have to extend TableRow and add this code to it. Call this when you need to add the row and pass in the data in the first params.