如何在 Android 的 tableLayout 中动态添加一行

新手上路,请多包涵

我有一个从网页获取产品列表的函数,我想在 tableLayout 中为列表的每个元素添加一行。

 public void getProductsOfCategory() throws IOException{
        new Thread(){
            public void run(){
                //background code...
                try {
                    Bundle extras = getIntent().getExtras();
                    String categoryName = extras.getString("categoryName");

                    HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/users/getProductsOfCategory.json?category="+categoryName);
                    HttpResponse httpresp = httpClient.execute(httpget);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    httpresp.getEntity().writeTo(baos);
                    final String content = new String(baos.toByteArray());
                    CategoryActivity.this.runOnUiThread(new Runnable(){
                        public void run(){
                            //foreground code (UI)
                            //update user interface, for example, showing messages
                            try {
                                JSONObject jObject = new JSONObject(content);
                                JSONArray productsList = jObject.getJSONArray("response");
                                for(int i=0; i<productsList.length();i++){
                                    JSONObject product = productsList.getJSONObject(i);
                                    JSONObject productData = product.getJSONObject("Product");
                                    String productDescription = productData.getString("description");
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

在我的布局 xml 文件中,我定义了这样的表格布局:

 <TableLayout
            android:id="@+id/tableOfProducts"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/productDescription"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:paddingBottom="7dp"
                android:paddingLeft="14dp"
                android:paddingRight="14dp"
                android:paddingTop="7dp"
                android:textSize="20dp" />

        </TableLayout>

我想我必须在 for 循环中添加一些额外的代码,为每个元素添加一个新行和一个新的文本视图,并使用包含产品描述的字符串设置文本视图的内容。我怎样才能做到这一点?

原文由 Julia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 923
2 个回答

检查一下,这是动态创建表行的一般方法。相应地修改它

文件

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/main_table"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</TableLayout>

Java部分

TableLayout t1;

TableLayout tl = (TableLayout) findViewById(R.id.main_table);

创建表格行标题以保存列标题

TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.GRAY);        // part1
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));

我在表行中添加了两个数据部分

TextView label_hello = new TextView(this);
         label_hello.setId(20);
         label_hello.setText("HELLO");
         label_hello.setTextColor(Color.WHITE);          // part2
         label_hello.setPadding(5, 5, 5, 5);
         tr_head.addView(label_hello);// add the column to the table row here

         TextView label_android = new TextView(this);    // part3
         label_android.setId(21);// define id that must be unique
         label_android.setText("ANDROID..!!"); // set the text for the header
         label_android.setTextColor(Color.WHITE); // set the color
         label_android.setPadding(5, 5, 5, 5); // set the padding (if required)
         tr_head.addView(label_android); // add the column to the table row here

在将列添加到表行之后,是时候将表行添加到我们在开始时获取的主表布局了

tl.addView(tr_head, new TableLayout.LayoutParams(
                 LayoutParams.FILL_PARENT,                    //part4
                 LayoutParams.MATCH_CONTENT));

编辑:您可以在您的代码中执行以下操作

 TextView[] textArray = new TextView[productsList.length()];
 TableRow[] tr_head = new TableRow[productsList.length()];

 for(int i=0; i<productsList.length();i++){
 JSONObject product = productsList.getJSONObject(i);
 JSONObject productData = product.getJSONObject("Product");
 String productDescription = productData.getString("description");

//Create the tablerows
tr_head[i] = new TableRow(this);
tr_head[i].setId(i+1);
tr_head[i].setBackgroundColor(Color.GRAY);
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));

 // Here create the TextView dynamically

 textArray[i] = new TextView(this);
         textArray[i].setId(i+111);
         textArray[i].setText(productDescription);
         textArray[i].setTextColor(Color.WHITE);
         textArray[i].setPadding(5, 5, 5, 5);
         tr_head[i].addView(textArray[i]);

// 将每个表格行添加到表格布局

tl.addView(tr_head[i], new TableLayout.LayoutParams(
                     LayoutParams.MATCH_PARENT,
                     LayoutParams.WRAP_CONTENT));

} // end of for loop

创建 TextView 和 TableRow 数组不是必需的。 You can just include part1 , part2 , part3 (if you need more than 1 field) and part4 inside your for loop.

原文由 Aniruddha 发布,翻译遵循 CC BY-SA 3.0 许可协议

看,我认为你必须修改你的 xml 以将行添加到你的 tableview:

一、打气筒:

  LayoutInflater inflater = mContext.getLayoutInflater();

或以这种方式:

  LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 //Here you can set up the layoutparameters from your tableview and the rowview.
 //Maybe you don't have to modify nothing from the parameters of your tableview so
 //you can dismiss it.

 TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
 TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

 //Here were we take the tablelayout from your xml
 TableLayout tableLayout = (TableLayout)inflater.inflate(R.layout.tableOfProducts, null);

 //Like a told you before, maybe you don't need set the parameters of the tablelayout
 //so you can comment next line.
 tableLayout.setLayoutParams(this.tableParams);

 TableRow tableRow = new TableRow(context);
 tableRow.setLayoutParams(this.tableParams);

 //Here you have to create and modify the new textview.
 TextView textView = new TextView(context);
 textView.setLayoutParams(this.rowParams);

 tableRow.addView(textView);

 tableLayout.addView(tableRow);

如果您需要更多帮助,请告诉我,如果有帮助,请给我打分!!! ;) Un saludo Gallega! O como se dice en gallego: una aperta!

原文由 Juan Pedro Martinez 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题