在while循环中创建视图并将其添加到外部布局中

时间:2014-10-03 10:05:37

标签: android

我有两个游标cursorcursordet,第二个游标位于第一个游标内。在 cursordet,我正在创建两个文本视图,向其中添加文本,然后将这些文本视图添加到第tr行。我希望将这一行添加到游标的while循环之外的表格布局中,但我得到一个无法解析tl.addView(tr);上的符号'tr'。有没有办法让tr公开或使其成为循环的输出?到目前为止,这是我的代码:

while (cursor.moveToNext()){

        TextView textOrdrID = new TextView(this);
        textOrdrID.setTextColor(Color.WHITE);
        textOrdrID.setTextSize(25);

        String id = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERS_ID));

        while (cursordet.moveToNext()) {

            TableRow tr = new TableRow(this);
            tr.setClickable(true);

            TextView textOrdrProdName = new TextView(this);
            textOrdrProdName.setTextColor(Color.WHITE);
            textOrdrProdName.setTextSize(25);

            TextView textOrdrProdPrice = new TextView(this);
            textOrdrProdPrice.setTextColor(Color.WHITE);
            textOrdrProdPrice.setTextSize(25);

            String prodname = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERSDET_PRODNAME));
            String price = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERSDET_PRICE));

            textOrdrID.append(prodname);

            tr.addView(textOrdrProdName);
            tr.addView(textOrdrPrice);
        }

        textOrdrID.append("Code:" + " " + id); 
        ordersdetLayout.addView(textOrdrID);
        tl.addView(tr);     

    }

1 个答案:

答案 0 :(得分:1)

尝试这样......

while (cursor.moveToNext()){

        TextView textOrdrID = new TextView(this);
        textOrdrID.setTextColor(Color.WHITE);
        textOrdrID.setTextSize(25);

        String id = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERS_ID));

        TableRow tr = null;
        while (cursordet.moveToNext()) {

            tr = new TableRow(this);
            tr.setClickable(true);

            TextView textOrdrProdName = new TextView(this);
            textOrdrProdName.setTextColor(Color.WHITE);
            textOrdrProdName.setTextSize(25);

            TextView textOrdrProdPrice = new TextView(this);
            textOrdrProdPrice.setTextColor(Color.WHITE);
            textOrdrProdPrice.setTextSize(25);

            String prodname = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERSDET_PRODNAME));
            String price = cursor.getString(cursor.getColumnIndex(COLUMN_ORDERSDET_PRICE));

            textOrdrID.append(prodname);

            tr.addView(textOrdrProdName);
            tr.addView(textOrdrPrice);
        }

        textOrdrID.append("Code:" + " " + id); 
        ordersdetLayout.addView(textOrdrID);
        if(tr != null)
             tl.addView(tr);     

    }