Динамически созданная TableRow, а затем RelativeLayout не отображается

Я перебираю результаты запроса, создающего RelativeLayouts в TableRows. Если я попытаюсь установить LayoutParams для RelativeLayout, ничего не появится и не будет ошибок. Если я этого не сделаю, все появится, но с макетом, установленным на WRAP_CONTENT. Я пробовал несколько примеров и не могу заставить его работать. Ниже мой код:

            TableLayout tblItems = (TableLayout) findViewById(R.id.tblItems);

            // Fields from the database (projection)
            String[] projection = new String[] { ItemsTable.ITEM_ID,
                                                ItemsTable.ITEM_NAME,
                                                ItemsTable.ITEM_PRICE,
                                                ItemsTable.ITEM_PICTURE };          
            Cursor cursor = getContentResolver().query(ItemsTable.CONTENT_URI, projection, null, null, null);                   
            startManagingCursor(cursor);        

            // Establish the item mapping
//          String[] columns = new String[] {"name", "price"};
//          int[] to = new int[] {R.id.tv_description, R.id.tv_price};

//          adapter = new SimpleCursorAdapter(this, R.layout.item_list_select, cursor, columns, to, 0);
//          lvSelectItems.setAdapter(adapter);

/*          
            adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { 

                public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
                    if(columnIndex == cursor.getColumnIndexOrThrow(OrderDetailTable.ORDERDETAIL_PRICE)) { 

                  //          String createDate = aCursor.getString(aColumnIndex); 
                  //          TextView textView = (TextView) aView; 
                  //          textView.setText("Create date: " + MyFormatterHelper.formatDate(getApplicationContext(), createDate)); 

                            double total = cursor.getDouble(columnIndex);
                            TextView textView = (TextView) view;
                            textView.setText("$" + String.format("%.2f",dRound(total, 2)));

                            return true; 
                    } 
                    return false; 
                } 

            });
*/          
            // tblItems

            int totalRows = 0;
            int tcolumn = 1;

            int numItems = cursor.getCount();
            double tempRow = numItems / 2;

            if (numItems > 0) {
                itemsFound = true;
            } else {
                itemsFound = false;
            }

            long iPart;  // Integer part
            double fPart;  // Fractional part
            boolean ifFirst = true;

            // Get user input
            iPart = (long) tempRow;
            fPart = tempRow - iPart;

            if (fPart > 0) {
                totalRows = (int) (iPart + 1);
            } else {
                totalRows = (int) iPart;
            }

            TableRow row = null;

            cursor.moveToFirst(); 
            while (cursor.isAfterLast() == false)  
            { 
                // tblItems    // TableLayout
                // TableRow
                // RelativeLayout
                // ImageView
                // TextView
                // TextView

                if (ifFirst) {
                    // create a new TableRow
                    row = new TableRow(this);
                    ifFirst = false;
                }

                // Creating a new RelativeLayout
                RelativeLayout relativeLayout = new RelativeLayout(this);


                // Defining the RelativeLayout layout parameters.
                // In this case I want to fill its parent
                RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);   

                rlp.setMargins(5, 5, 5, 5);

                relativeLayout.setPadding(5, 5, 5, 5);
                relativeLayout.setBackgroundResource(R.drawable.grpbx_item);

                row.addView(relativeLayout, rlp);

                // add text view
                ImageView imgPic = new ImageView(this);
                imgPic.setBackgroundResource(R.drawable.takepic);
                imgPic.setPadding(0, 0, 0, 0);
                relativeLayout.addView(imgPic);

                // add text view
                TextView tvName = new TextView(this);
                String name = cursor.getString(cursor.getColumnIndexOrThrow(ItemsTable.ITEM_NAME));
                tvName.setText("" + name);

             // Defining the layout parameters of the TextView
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.CENTER_IN_PARENT);

           //     RelativeLayout.

                // Setting the parameters on the TextView
                tvName.setLayoutParams(lp);
                relativeLayout.addView(tvName);

                // add text view
                double iPrice = cursor.getDouble(cursor.getColumnIndexOrThrow(ItemsTable.ITEM_PRICE));

                TextView tvPrice = new TextView(this);
                tvPrice.setText("$" + String.format("%.2f",dRound(iPrice, 2)));
                relativeLayout.addView(tvPrice);


                tcolumn++;

                numItems--;

                if (tcolumn == 3) {
                    // add the TableRow to the TableLayout
                    tblItems.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

                    // create a new TableRow
                    row = new TableRow(this);
                    tcolumn = 1;
                } else {
                    if (numItems == 0) {
                        // add the TableRow to the TableLayout
                        tblItems.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    }
                }

                // Move to the next record
                cursor.moveToNext(); 
            } 

        }

person user1713455    schedule 02.10.2012    source источник


Ответы (1)


Если я попытаюсь установить параметры макета для relativeLayout, ничего не появится и не будет ошибок. Если я этого не сделаю, все появится, но с макетом, установленным на обертку содержимого.

Вы используете неправильный LayoutParams вместо RelativeLayout. Ты используешь:

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);   
row.addView(relativeLayout, rlp);

но поскольку родителем этого RelativeLayout является TableRow, вы должны использовать TableRow.LayoutParams:

TableRow.LayoutParams rlp = new TableRow.LayoutParams(
                        TableRow.LayoutParams.FILL_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT);   
row.addView(relativeLayout, rlp);
person user    schedule 03.10.2012
comment
Спасибо за ответ. Я попробую. - person user1713455; 11.10.2012
comment
@zlgdev Опубликуйте новый вопрос о вашей текущей ситуации. - person user; 17.02.2014