动态创建控件,还是创建控件;只不过,是在程序中创建控件;创建控件就好像在屏幕上画画一样。首先,要一张纸;然后,再在这个框架里画自己想画的事物。在android里,这张纸就是一个容器,常用的LinearLayout、RelativeLayout、FrameLayout等等;在android里,自己想画的事物就是一些view,常用的TextView、EditView、Button等等。

  知道了大体思路之后,就要说细节了;

  第一是容器,创建一个容器(这里用LinearLayout举例);

LinearLayout lLayout = new LinearLayout(this);

(这里的this是一个Context变量);

  第二是容器的细节,也就是属性部分;比如,容器里的控件是怎样排的;

lLayout.setOrientation(LinearLayout.VERTICAL);

还有的就不说了。

  第三是容器里的控件,创建自己想要的控件;比如,

EditText editText = new EditText(this);Button button = new Button(this);//这里的this都是一个Context变量;

  第四是容器的细节,就是设置容器的属性;

editText.setLines(3); editText.setGravity(Gravity.TOP|Gravity.LEFT);button.setText("插入随机表情");
button.setTextColor(Color.rgb(255,255,255)); //白色button.getBackground().setAlpha(int); int 在0-255之间,255为不透明

  第五是将控件加入到容器当中去;

LinearLayout.LayoutParams lParams = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);//这个属性是设置空间的长宽,其实还可以设置其他的控件的其他属性;lLayout.addView(editText, lParams);lLayout.addView(button, lParams);

  第六是将容器将加入ContentView中;

setContentView(lLayout);

  源代码:这个代码就不注释了,看了上面的六步应该会清楚下面的程序的:

public class MainActivity extends Activity {  /** Called when the activity is first created. */  @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    // setContentView(R.layout.main);    LinearLayout lLayout = new LinearLayout(this);    lLayout.setOrientation(LinearLayout.VERTICAL);    EditText editText = new EditText(this);    editText.setLines(3);    editText.setGravity(Gravity.TOP|Gravity.LEFT);    LinearLayout.LayoutParams lParams = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);    lLayout.addView(editText, lParams);    Button button = new Button(this);    button.setText("插入随机表情");    lLayout.addView(button, lParams);    setContentView(lLayout);  }}

更多相关文章

  1. Android读写XML(下)——创建XML文档
  2. android 按百分比设置布局
  3. Android(安卓)Handler 异步消息处理机制的妙用 创建强大的图片加
  4. Android应用开发——TextView控件属性列表
  5. (4.1.21.4)Android(安卓)Handler 异步消息处理机制的妙用 创建强大
  6. Android(安卓)学习日志 2 :创建虚拟机,运行第一个Hello Android程
  7. Android(安卓)JNI打印c\c++日志信息
  8. Android常用命令之创建avd
  9. android:layout_weight属性详解

随机推荐

  1. Android动画循环弹动cycleInterpolator
  2. android批量插入数据效率对比
  3. Android - adb : logcat / shell / app_p
  4. Android中Activity共享变量的另一方法:App
  5. Android实现底部弹出按钮菜单升级版
  6. fastboot 详解
  7. Android系统开发小问题-启动过程中android
  8. android之有返回结果跳转intent
  9. 利用drozer进行Android渗透测试 - AndroS
  10. Android(安卓)Https 双向认证