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.

  • 相关阅读:
    mojoportal学习——文章翻译之SmartCombo
    windows froms 程序打包 (转载)
    [笔记]LCD1602 Display Experiment
    [笔记] JLink V8固件烧录指导
    [笔记]NiosII之Count Binary
    [笔记]DE2115 LCD1602字符的显示
    [笔记]What is HDBaseT
    [笔记]Inrush Current Case
    [笔记]远传中继的实现
    [笔记]RunningLED Experiment
  • 原文地址:https://www.cnblogs.com/androidez/p/2892456.html
Copyright © 2011-2022 走看看