Android(安卓)动态添加View
16lz
2021-12-04
Android中可以从xml中读取布局,但是动态添加有时方便很多
首先需要的View
private Context mContext = null;private TextView view1 = null;private TextView view2 = null;private TextView view3 = null;private RelativeLayout layout = null;
在onCreat中
layout = (RelativeLayout) findViewById(R.id.layout);mContext = this;
第一种,直接添加,没有布局要求的
private void addView1() {layout = (RelativeLayout) findViewById(R.id.layout);view1 = new TextView(mContext);view1.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));view1.setText("TextView1");view1.setTextColor(0xFF000000);layout.addView(view1);}
第二种,规定在第一个的下方并且水平居中
private void addView2() {view2 = new TextView(mContext);RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);params.addRule(RelativeLayout.CENTER_HORIZONTAL);view1.setId(1);params.addRule(RelativeLayout.BELOW, 1);view2.setLayoutParams(params);view2.setText("TextView2");layout.addView(view2);}
第三种,规定顶端和左边的距离
private void addView3() {view3 = new TextView(mContext);MarginLayoutParams mlp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);mlp.setMargins(50, 200, 0, 0);view3.setLayoutParams(new RelativeLayout.LayoutParams(mlp));view3.setText("TextView3");layout.addView(view3);}
最后可以删除layout内的view
private void removeView2() {layout.removeViewAt(1);}layout内view的放置就和数组一样,第一个的位置是0,第二个是1,以此类推
更多相关文章
- android Activity单元测试
- Android(安卓)WebView JavaScript交互
- Android(安卓)N共享文件报错:android.os.FileUriExposedException
- Android(安卓)Service 的添加流程
- android入门级小软件身高体重计算器源代码,初学者可以看看~
- "Failed to fetch URL https://dl-ssl.google.com/android/repos
- android 编译各cpu芯片的so库
- android 添加桌面窗口小部件(托至桌面需要点击按钮才能生成的)
- 推荐几个ListView下拉刷新