我正在尝试在执行期间向空表中添加一堆行。我尝试使用一些测试代码,但由于某种原因屏幕保持空白。如果我在 .XML 中有元素,它们会显示,但不会显示表格本身,除非我也在 .XML 文件中添加一些行/元素。
非常感谢您的帮助。
我的类扩展了 Activity。
这是更新表格的代码:
public Runnable UpdateUserList = new Runnable() {
public void run() {
TableLayout userTable = (TableLayout) findViewById(R.id.listOfUsers);
for (String user : userNames) {
TableRow row = new TableRow(getBaseContext());
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TextView field = new TextView(getBaseContext());
field.setText(user);
field.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
row.addView(field);
userTable.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
}
};
我以这种方式从线程调用使用处理程序的代码:
mHandler.post(UpdateUserList);
代码确实运行并且没有打印任何错误。
这是 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:background="@drawable/main_bg"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_marginTop="10px" android:gravity="center_horizontal"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="@string/userList"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="25px" />
</LinearLayout>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/listOfUsers">
</TableLayout>
</LinearLayout>
任何帮助都会非常有用。我现在很困。
编辑:使用 ListView
private Runnable UpdateUserList = new Runnable() {
public void run() {
ListView userTable = (ListView) findViewById(R.id.listOfUsers);
userTable.setAdapter(new ArrayAdapter<String>(getBaseContext(),
R.layout.connectserver, userNames));
}
};
还有 XML:
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/listOfUsers" />
而不是 TableLayout。
最佳答案
我认为您会发现使用 List 而不是 TableLayout 更容易。一种是为容纳多个项目而构建的,并且可以轻松地与 java.util.List 或 Array 集成。其次,更重要的是,如果您拥有的项目多于可见的项目,那么内存效率会更高。
对于列表,它只实例化可见行的 View + 1 个 N 列表。如果您使用 TableLayout 显示相同的列表,它实例化 N 个 View 。因此,随着列表的增长,TableLayout 的内存使用量也会增加。列表不是这样。无论您在该列表中有多少项目,都是一样的。
此外,它还提供了更好的方法来跟踪用户单击某个项目时选择了哪些项目。 TableLayout 在这方面没有提供任何帮助,因此您必须使用自己的机制来进行选择。
关于android - 在执行期间向空 TableLayout 添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384071/