• 通过代码生成布局文件


    通过代码生成上面的布局为:

     1 package cn.android.codeui;
     2
     3 import android.app.Activity;
     4 import android.os.Bundle;
     5 import android.view.ViewGroup.LayoutParams;
     6 import android.widget.Button;
     7 import android.widget.EditText;
     8 import android.widget.LinearLayout;
     9 import android.widget.TextView;
    10 
    11 public class MainActivity extends Activity {
    12     /** Called when the activity is first created. */
    13     @Override
    14     public void onCreate(Bundle savedInstanceState) {
    15         super.onCreate(savedInstanceState);
    16         
    17         LinearLayout linearlayout = new LinearLayout(this);
    18         linearlayout.setOrientation(LinearLayout.VERTICAL);
    19         
    20         TextView tv = new TextView(this);
    21         tv.setText("姓名");
    22         LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    23         linearlayout.addView(tv, params);
    24         
    25         EditText et = new EditText(this);
    26         linearlayout.addView(et, params);
    27         
    28         Button bt = new Button(this);
    29         bt.setText("确定");
    30         params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    31         linearlayout.addView(bt, params);
    32         
    33         params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    34         setContentView(linearlayout, params);
    35     }
    36 }

    小结:一个控件只能有一个父元素,如果多次添加则会报出异常:
      

    E/AndroidRuntime(23954):
    java.lang.RuntimeException: Unable to start activity ComponentInfo{cn.android.codeui/cn.android.codeui.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

  • 相关阅读:
    maven项目编译漏掉src/main/java下的xml配置文件
    读《架构探险——从零开始写Java Web框架》
    使用generator自动生成Mybatis映射配置文件
    git项目添加.gitigore文件
    git-bash下, 启动sshd
    git-bash.exe参数
    少估了一分, 还算不错
    python常用库
    Linux下python pip手动安装笔记
    python学习笔记
  • 原文地址:https://www.cnblogs.com/androidez/p/2892456.html
Copyright © 2020-2023  润新知