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.

  • 相关阅读:
    NOIP模拟题 管道
    NOIP模拟题 序列
    NOIP模拟题 栅栏
    NOIP模拟题 斐波那契数列
    CodeForces 797F Mice and Holes
    CodeForces 589H Tourist Guide
    CERC2016 爵士之旅 Jazz Journey
    BZOJ3832 Rally
    BZOJ1061 NOI2008 志愿者招募
    js数组的操作
  • 原文地址:https://www.cnblogs.com/androidez/p/2892456.html
Copyright © 2011-2022 走看看