【问题标题】:Android: Error in adding table layout dynamicallyAndroid:动态添加表格布局时出错
【发布时间】:2015-01-22 00:49:49
【问题描述】:

我正在尝试将表格布局动态添加到 xml 文件中,而 LayoutParams 导致错误。

活动代码:

package com.pyrospiral.android.tabbedtimetable;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;


public class TimeTableWeek extends Activity {

TextView subname;
TextView timing;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_time_table_week);

    //Create text view
    TextView text = new TextView(this);
    text.setText("aaaaa");

    //Layout params
    LayoutParams params = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    android.widget.TableRow.LayoutParams trparams = new TableRow.LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT, android.widget.TableRow.LayoutParams.WRAP_CONTENT);

    //Find table in xml
    TableLayout table = (TableLayout) findViewById(R.id.gridtable);
    table.setLayoutParams(params);

    //Create table row

    TableRow row = new TableRow(this);
    row.setLayoutParams(trparams);
    row.setBackgroundColor(Color.GREEN);
    row.addView(text);




}

}

XML 文件:

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/gridtable">


    </TableLayout>


</ScrollView>

错误:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.pyrospiral.android.tabbedtimetable, PID: 26691
java.lang.ClassCastException: android.widget.TableLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams

将 TableLayout.LayoutParams 更改为 FrameLayout.LayoutParams 不会出错,但也不会显示任何内容。

【问题讨论】:

    标签: android tablelayout


    【解决方案1】:

    你需要把TableLayout改成FrameLayout,像这样:

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
    

    要查看您的文本,您必须将该行添加到表格中

    table.addView(row);
    

    【讨论】:

    • 谢谢它的工作,虽然如果我尝试在循环中这样做,它会说“指定的孩子已经有一个父母。你必须首先在孩子的父母上调用 removeView()。”有解决办法吗?
    • 阅读this 答案。问题出在您的代码中。也许您多次添加同一行,您需要创建新行。
    【解决方案2】:

    表格的布局参数已经在你的 XML 中定义了,所以我认为你的变量“params”是不必要的。

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多