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