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

6
我有一个功能可以从网页获取产品列表,我想为列表中的每个元素在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循环中添加一些额外的代码,为每个元素添加一个新行和一个新的textview,并使用包含产品描述的字符串设置textview的内容。

我该怎么做呢?

5个回答

17

看这里,这是动态创建表格行的一般方式。相应地进行修改。

XML文件

<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数组并不是必需的。您只需要在for循环中包含part1part2part3(如果您需要多个字段)和part4即可。


1
@JuanPedroMartinez 请使用英语评论,这样每个人都可以理解。 - Aniruddha
他想说你做得很好。但是它给了我一个错误,我不知道该怎么解决。 :) - Julia
tr_head.addView(textArray[i]); tr_head没有addView方法 - Julia
现在这个问题已经解决了,但是当我运行应用程序时,它会崩溃。日志记录器显示 nullPointerException。 - Julia
我认为问题出在这里:tr_head[i] = new TableRow(this); 我可以放置“this”,因为函数是Runnable,但会出现错误。所以我放置了“getApplicationContext()”。 - Julia
显示剩余3条评论

1
看,我认为你需要修改你的XML文件以向你的表格视图添加行:
首先,使用inflater:
 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);

如果您需要更多帮助,请告诉我,如果有帮助,请评价我!!!;) 一个问候 Gallega!或者用加利西亚语说:una aperta!

这给我带来了问题,因为我的函数是可运行的,在这一行:LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 你猜为什么?非常感谢 ;) - Julia
对于LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE),请使用yourActivityName.this而不是仅使用"this"。 - Pankaj Deshpande
潘卡吉上次有帮助你解决问题吗?如果没有,我认为还有其他解决方案。 - Juan Pedro Martinez
嗨,Aniruddha,我正在尝试它,但它不起作用。错误在这里:tr_head.addView(textArray[i]); - Julia
@Julia 我已经更新了答案,请现在检查并告诉我。 - Aniruddha
显示剩余2条评论

0

我自己也是新手Android开发者,之前一直使用Python/Gtk,如果不能按照Model/View/Presenter的思路来思考问题,我就会迷失方向。

我找到了一个有用的方法,让我重新回到这种视角,即使与表格无关,我相信它也可以扩展到那里(我想this page对我来说是一个很好的起点)。

首先在你的片段(或活动)中声明这两个对象:

List<String> stringList;  // think of it as the model.
ArrayAdapter<String> listAdapter;  // and this would be the presenter

在片段构造函数中定义模型:
stringList = new ArrayList<>();

接下来,当我的片段的onCreateView被调用时,我会这样做(如果您使用的是Activity而不是Fragment,请相应地进行编辑):
View rootView = inflater.inflate(R.layout.fragment_taxonomy, container, false);
ListView mainListView = rootView.findViewById(R.id.taxonomy_results);

// Create ArrayAdapter using the string list.  think of it as the presenter.
// see how it's being handled a model and a view.
listAdapter = new ArrayAdapter<>(
        rootView.getContext(), R.layout.textrow, stringList);

// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );

textrow.xml 是一个额外的布局,每次我向 stringList 模型中添加元素时都会被重复使用。

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

在代码的其余部分,我只与listAdapter“交流”,并且我只需要它的两个addclear方法,以添加元素或清除列表。

0

有许多方法可以做到这一点。首先,为了最小化您的代码,请创建一个XML文件,初始化TableRow及其属性(TextView也应包括在内)。然后,在与活动链接的目标XML文件中,您只需要创建TableLayout

主要是创建LayoutInflater,将项目链接在一起。然后,尽可能创建多个TableRow。最后,每个具有唯一变量的TableRow都应使用addView()链接到您在XML中创建的TableLayout

更多信息,请参见此处。https://github.com/AreejTurky/Dynamic-TableRow-Generation


0

为此,您需要为每一行创建一个XML文件,然后修改您的layout.xml文件,如下所示

<ScrollView>
  <LinearLayout orientation=vertical id="+id/rowHolder">
  </LinearLayout
</scrollview>

然后在for循环中,填充行布局并将其动态添加到rowHolder对象中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接