0
我有一個LinearLayout的xml文件,它包含一個TableLayout,後面包含TableRows,所以我希望在應用程序運行時以編程方式添加一個新的TableRow。TableLayout addView不起作用
所以我寫了下面的代碼使用addView方法,但我的代碼不起作用。
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout myRoot = (LinearLayout)findViewById(R.id.tbl_test);
TableRow a = new TableRow(this);
a.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myRoot.addView(a);
}
}
的xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical">
<TableLayout
android:id="@+id/tbl_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:stretchColumns="1"
>
<TableRow
android:id="@+id/tbr_test"
android:background="#ffffff" android:layout_margin="1dp">
<TextView android:layout_column="0" />
<TextView android:layout_column="1" />
<TextView android:layout_column="2" />
<TextView android:layout_column="3" />
</TableRow>
<TableRow
android:background="#ffffff"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp">
<TextView android:layout_column="0" />
<TextView android:layout_column="1" />
<Button/>
<Button/>
</TableRow>
<TableRow
android:background="#ffffff"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"
android:paddingRight="2dp">
<TextView android:layout_column="0" />
<TextView android:layout_column="1" />
<Button/>
<Button />
</TableRow>
<TableRow
android:background="#ffffff"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"
android:paddingRight="3dp">
<TextView android:layout_column="0" />
<TextView android:layout_column="1" />
<Button />
<Button />
</TableRow>
<TableRow
android:id="@+id/tbr"
android:background="#ffffff"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"
android:paddingRight="4dp">
<TextView android:layout_column="0" />
<TextView android:layout_column="1" />
<Button />
<Button/>
</TableRow>
</TableLayout>
</LinearLayout>
不,它不適用於我 – JavaFan
@JavaFan添加此後您有什麼問題。 – Ironman
沒問題,但沒有添加新行可能是因爲最小api設置爲8?但我添加這一行@TargetApi(Build.VERSION_CODES.HONEYCOMB) – JavaFan