如何在Android的tableLayout中动态添加一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24078275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a row dynamically in a tableLayout in Android
提问by Julia
I have a function who gets a list of products from a webpage, and I want to add a row in a tableLayout for each element of the list.
我有一个从网页获取产品列表的函数,我想在 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();
}
In my layout xml file I have defined the table layout like this:
在我的布局 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>
I imagine I have to add some extra code in the for loop, adding a new row and a new textview for each element, and setting the content of the text view with the string that has the description of the product. How can I do this?
我想我必须在 for 循环中添加一些额外的代码,为每个元素添加一个新行和一个新文本视图,并使用具有产品描述的字符串设置文本视图的内容。我怎样才能做到这一点?
回答by Aniruddha
Check this out, this is the general way of creating table rows dynamically. Modify it accordingly
看看这个,这是动态创建表行的一般方法。相应地修改它
XML file
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 PART
爪哇部分
TableLayout t1;
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
Create table row header to hold the column headings
创建表格行标题以保存列标题
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));
I'm adding two data sections to the table row
我正在向表格行添加两个数据部分
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
After adding the columns to the table row its time to add the table row the the main table layout that we fetched at the start
将列添加到表行后,是时候添加表行了,即我们在开始时获取的主表布局
tl.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, //part4
LayoutParams.MATCH_CONTENT));
EDIT : YOU CAN DO THE FOLLOWING IN YOUR CODE
编辑:您可以在代码中执行以下操作
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]);
// Add each table row to table layout
// 将每个表格行添加到表格布局
tl.addView(tr_head[i], new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
} // end of for loop
Creating the TextView and TableRow array are not necessary. You can just include part1
, part2
, part3
(if you need more than 1 field) and part4
inside your for loop.
不需要创建 TextView 和 TableRow 数组。您可以只包含part1
, part2
, part3
(如果您需要 1 个以上的字段)并part4
在您的 for 循环中。
回答by Juan Pedro Martinez
Look, i think you have to modify your xml to adding rows to your tableview:
看,我认为您必须修改您的 xml 以将行添加到您的 tableview:
First, the inflater:
一、充气机:
LayoutInflater inflater = mContext.getLayoutInflater();
or in this way:
或以这种方式:
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);
If you need more help, tell me, if it is helpful, rating me!!! ;) Un saludo Gallega! O como se dice en gallego: una aperta!
如果您需要更多帮助,请告诉我,如果有帮助,请给我评分!!!;) Un saludo Gallega!O como se dice en gallego: una aperta!
回答by Pankaj Deshpande
for this, you have to create one xml file for row, then you have to modify your layout.xml file like
为此,您必须为行创建一个 xml 文件,然后您必须修改 layout.xml 文件,例如
<ScrollView>
<LinearLayout orientation=vertical id="+id/rowHolder">
</LinearLayout
</scrollview>
Then in for loop, inflate the row layout and add it runtime to rowHolder object.
然后在 for 循环中,膨胀行布局并将其运行时添加到 rowHolder 对象。
回答by mariotomo
I'm new myself to Android, and after years with Python/Gtk, I'm lost if I can't think in terms of Model/View/Presenter.
我自己是 Android 新手,在使用 Python/Gtk 多年后,如果我无法在模型/视图/演示者方面思考,我会迷失方向。
one useful approach I managed to apply, it puts me back into that optics, and even if it's not relative to a Table, I'm quite sure it can be extended to that (I guess this pagewould be a good start, for me too).
我设法应用了一种有用的方法,它让我回到了那个光学中,即使它与表格无关,我也很确定它可以扩展到那个(我想这个页面对我来说是一个好的开始也)。
start by declaring the two objects in your fragment (or activity):
首先在您的片段(或活动)中声明两个对象:
List<String> stringList; // think of it as the model.
ArrayAdapter<String> listAdapter; // and this would be the presenter
define the model in the fragment constructor:
在片段构造函数中定义模型:
stringList = new ArrayList<>();
next, when the onCreateView of my fragment is invoked, I do this (edit correspondingly if you're using Activity, not Fragment):
接下来,当调用我的片段的 onCreateView 时,我会这样做(如果您使用的是活动,而不是片段,则相应地进行编辑):
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
is an extra layout which is being reused every time I add an element to the stringList
model.
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>
in the rest of the code, I only "talk" to listAdapter
, and I only need its two add
and clear
methods, to add elements, or for clearing the list.
在其余的代码中,我只与 进行“对话” listAdapter
,我只需要它的两个add
和clear
方法来添加元素或清除列表。