java - 在 TableLayout 中动态添加两个 TextView

标签 java android dynamic rows android-tablelayout

我正在尝试在表中动态添加行。我需要在每行中并排添加两个 TextView。这必须动态完成。我已经编写了动态创建行的代码。我无法在侧面添加第二个 TextView。

activity.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:stretchColumns="0,1"
    android:id="@+id/tableView" 
    android:layout_weight="1"         
    android:layout_height="wrap_content" 
    android:layout_width="match_parent">
</TableLayout>`

MainActivity.java

    TableLayout ll = (TableLayout) findViewById(R.id.tableView);
    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView qty = new TextView(this);
        qty.setText("10");
        row.addView(qty);
        ll.addView(row,i);
    }

最佳答案

您忘记设置LayoutParams:

TableLayout ll = (TableLayout) findViewById(R.id.tableView);
for (int i = 0; i < 2; i++) {

    TableRow row = new TableRow(this);
    row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

    TextView qty = new TextView(this);
    qty.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
    qty.setText("10");
    row.addView(qty);

    ll.addView(row);
}

关于java - 在 TableLayout 中动态添加两个 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47680026/

相关文章:

dynamic - 如何在Rust中清除libloading的内部缓存

ios - 我如何以编程方式创建动态文本字段

java - 确保 Web 服务处理异常并始终返回有效响应

android - 在 RxJava 2.0 中订阅 PublishSubject

android - 媒体播放器 : stop called in state 4

android - 所选 View 的默认选择器

java - 当 url 包含大括号字符时 Spring-boot Controller 出错

java - flutter 说它 'Could not resolve project'

java - Canvas.clipRegion(区域区域)已弃用

c# - 为什么这个 (null || !TryParse) 条件结果为 "use of unassigned local variable"?