Android:动态添加表格布局时出错

时间:2015-01-21 16:32:27

标签: android tablelayout

我正在尝试动态地将表格布局添加到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不会出错,但也不显示任何错误。

2 个答案:

答案 0 :(得分:0)

您需要将TableLayout更改为FrameLayout,如下所示:

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

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

table.addView(row);

答案 1 :(得分:0)

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