我没有得到多行。只显示一行。如何解决这个问题。
//活性
public class TableViewActivity extends AppCompatActivity {
TableLayout tableLayout;
TableRow tableRow;
TextView textView1, textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_view);
tableLayout = (TableLayout) findViewById(R.id.tableLayout);
tableRow = (TableRow) findViewById(R.id.tableRow2);
textView1 = (TextView) findViewById(R.id.TextViewRowTwo1);
textView2 = (TextView) findViewById(R.id.TextViewRowTwo2);
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Mahmud"));
students.add(new Student(2, "Saiful"));
students.add(new Student(3, "Monir"));
students.add(new Student(4, "Milton"));
for (int j = 0; j< students.size(); j++) {
textView1.setText(students.get(j).getId()+"");
textView2.setText(students.get(j).getName());
// TEXTVIEW
if(textView1.getParent()!=null)
((ViewGroup)textView1.getParent()).removeView(textView1); // <- fix
tableRow.addView(textView1);
if(textView2.getParent()!=null)
((ViewGroup)textView2.getParent()).removeView(textView2); // <- fix
tableRow.addView(textView2);
if(tableRow.getParent()!=null)
((ViewGroup)tableRow.getParent()).removeView(tableRow); // <- fix
tableLayout.addView(tableRow);
}
setContentView(tableLayout);
}
}
答案 0 :(得分:2)
您需要动态创建TableRow,每当您将值放入tablerow时,您需要将该tablerow添加到tablelayut。
for (int j = 0; j< students.size(); j++) {
TableRow tableRow = new TableRow(this);
textView1.setText(students.get(j).getId()+"");
textView2.setText(students.get(j).getName());
// TEXTVIEW
if(textView1.getParent()!=null)
((ViewGroup)textView1.getParent()).removeView(textView1); // <- fix
tableRow.addView(textView1);
tableLayout.addView(tableRow);
if(textView2.getParent()!=null)
((ViewGroup)textView2.getParent()).removeView(textView2); // <- fix
tableRow.addView(textView2);
tableLayout.addView(tableRow);
if(tableRow.getParent()!=null)
((ViewGroup)tableRow.getParent()).removeView(tableRow); // <- fix
tableLayout.addView(tableRow);
}
希望这对你有用。
答案 1 :(得分:0)
我认为在你的情况下使用ListView会更好。它更简单,旨在显示像学生一样的对象列表。
https://developer.android.com/guide/topics/ui/layout/listview.html