动态创建控件,还是创建控件;只不过,是在程序中创建控件;创建控件就好像在屏幕上画画一样。首先,要一张纸;然后,再在这个框架里画自己想画的事物。在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应用开发——TextView控件属性列表
  2. 【android】GridView几个比较实用的属性以及需要注意的问题
  3. edittext的imeOptions属性和android软键盘的使用
  4. android:ellipsize属性
  5. Android 控件四 EditText 控件
  6. Android中TextView和EditView常用属性设置

随机推荐

  1. 禁止其他应用访问自己的组件
  2. Android(安卓)展示本地或网络pdf文件
  3. 解决android sdk docs帮助文档打开慢的问
  4. RotateAnimation类:旋转变化动画类
  5. Android(安卓)Cannot add task 'reportSo
  6. Android开发规范:JavaDoc
  7. Android(安卓)4.0:Unable to find a 'user
  8. 一起学android之如何获取手机程序列表以
  9. Android(安卓)Studio创建RelativeLayout
  10. android IllegalStateException