我有一个从网页获取产品列表的函数,我想在 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 许可协议
检查一下,这是动态创建表行的一般方法。相应地修改它
文件
Java部分
创建表格行标题以保存列标题
我在表行中添加了两个数据部分
在将列添加到表行之后,是时候将表行添加到我们在开始时获取的主表布局了
编辑:您可以在您的代码中执行以下操作
// 将每个表格行添加到表格布局
创建 TextView 和 TableRow 数组不是必需的。 You can just include
part1
,part2
,part3
(if you need more than 1 field) andpart4
inside your for loop.