Android的基本UI界面一般都是在xml文件中定义好,然后通过activity的setContentView来显示在界面上,这是Android UI的最简单的构建方式。其实,为了实现更加复杂和更加灵活的UI界面,往往需要动态生成UI界面,甚至根据用户的点击或者配置,动态地改变UI,本文即介绍该技巧。


假设Android工程的一个xml文件名为activity_main.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"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/Dynam