zoukankan      html  css  js  c++  java
  • 通过代码生成布局文件

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

     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.

  • 相关阅读:
    tensorrt 中的一些基本概念 Logger, Context, Engine, Builder, Network, Parser 知识梳理
    JavaWeb之互联网通信流程
    JSON
    JS之BOM编程History和location对象
    JS之将当前窗口设置为顶级窗口
    JS之BOM编程--弹出消息框和确认框
    JS之BOM编程window的open和close
    JS之内置支持类Array
    多次使用setInterval方法导致clearInterval不能成功关闭
    JS之周期函数setInterval
  • 原文地址:https://www.cnblogs.com/androidez/p/2892456.html
Copyright © 2011-2022 走看看