【发布时间】: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