簡體   English   中英

動態將TableRow添加到linearlayout android

[英]Add TableRow dynamically to linearlayout android

我需要在我的應用程序中將一些表格行動態添加到linearlayout中。 我寫這段代碼:

LinearLayout tabella = (LinearLayout) findViewById(R.id.tabella_contatori);

    for(int i =0; i<array_list.size(); i++){
        TableRow row = new TableRow(getApplicationContext());
        row.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        TextView data = new TextView(getApplicationContext());
        data.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.2f));
        data.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
        data.setTextColor(Color.BLACK);
        data.setBackgroundColor(Color.WHITE);
        data.setPadding(2, 0, 0, 0);
        data.setText("asd");

        row.addView(data);
        tabella.addView(row);
    }
}

但是,當我打開該應用程序時,沒有任何反應。 我已經檢查了array_list.size是否大於0。該怎么辦? 謝謝,Mattia

問題出在您的TextView布局參數中。 類型應為TableRow.LayoutParams,而不是LinearLayout.LayoutParams。 data.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));

進行表格布局,並嘗試在main.xml中使用它...

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myTableLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
     <TableRow
          android:layout_width="fill_parent"
          android:layout_height="wrap_content">

          <TextView android:text="Some Text"/>

     </TableRow>
</TableLayout>

在您的活動中

this.setContentView(R.layout.main);

/* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);
     /* Create a new row to be added. */
     TableRow tr = new TableRow(this);
     tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
          /* Create a TextView to be the row-content. */    

        TextView data = new TextView(getApplicationContext());
        data.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 0.2f));
        data.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
        data.setTextColor(Color.BLACK);
        data.setBackgroundColor(Color.WHITE);
        data.setPadding(2, 0, 0, 0);
        data.setText("asd");

          /* Add TextView to row. */
          tr.addView(data);
    /* Add row to TableLayout. */
    tl.addView(tr,new TableLayout.LayoutParams(
          LayoutParams.FILL_PARENT,
          LayoutParams.WRAP_CONTENT));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM