Android(安卓)在程序中动态添加 View 布局或控件
16lz
2021-01-24
有时我们需要在程序中动态添加布局或控件等,下面用程序来展示一下相应的方法:
1、addView
添加View到布局容器
2、removeView
在布局容器中删掉已有的View
3、LayoutParams
设置View的大小位置
下面来看一个demo;
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//setContentView(R.layout.activity_main);LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);LinearLayout lineLayout = new LinearLayout(this);lineLayout.setOrientation(LinearLayout.VERTICAL);lineLayout.setLayoutParams(params);lineLayout.setGravity(Gravity.TOP );addView(lineLayout);setContentView(lineLayout);} private void addView(final LinearLayout lineLayout){final TextView showText = new TextView(this);showText.setTextColor(Color.GREEN);showText.setTextSize(30);showText.setId(10001);//设置 idshowText.setText("我是在程序中添加的第一个文本");showText.setBackgroundColor(Color.GRAY);// set 文本大小LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);//set 四周距离params.setMargins(10, 10, 10, 10); showText.setLayoutParams(params);//添加文本到主布局lineLayout.addView(showText ); //创建按钮Button btn = new Button(this);btn.setText("点击删除文本");btn.setBackgroundColor(Color.GRAY) ;LinearLayout.LayoutParams btn_params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); btn_params.setMargins(0, 60, 60, 0);btn_params.gravity = Gravity.CENTER_HORIZONTAL;btn.setLayoutParams(btn_params);// 动态添加按钮到主布局lineLayout.addView(btn);//点击按钮 动态删除文本btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(null != lineLayout.findViewById(10001)){lineLayout.removeView(showText);}else{Toast.makeText(MainActivity.this, "文本已被删除", Toast.LENGTH_SHORT).show();}}}); //动态创建一个相对布局RelativeLayout relaLayout = new RelativeLayout(this);relaLayout.setBackgroundColor(Color.BLUE); RelativeLayout.LayoutParams lp11 = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 120); relaLayout.setLayoutParams(lp11); //动态创建一个文本final TextView RelaText = new TextView(this);RelaText.setTextColor(Color.GREEN);RelaText.setTextSize(20);RelaText.setText("我是在程序中添加的第二个文本,在相对布局中");RelaText.setBackgroundColor(Color.GRAY);//设置文本的布局 RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp2.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); lp2.setMargins(10, 10, 10, 10); //将文本添加到相对布局中relaLayout.addView(RelaText,lp2);//将这个布局添加到主布局中 lineLayout.addView(relaLayout); }}
看一下效果图片:
点击按钮前:
点击按钮删除上面的文本:
http://download.csdn.net/detail/q610098308/9293621
更多相关文章
- Android安卓布局简介
- [Android] ExpandableListView 子目录点击不响应,解决
- ExpandableListView 怎么和其他组件相互整合布局
- Android(安卓)-- 动态添加布局
- 【Mark 】AndroidStudio_移动应用开发
- Android(安卓)ViewPager多页面滑动切换以及动画效果
- Android:Actionbar杂记
- Android仿微信实现下拉列表
- 【Android文档】Android界面绘制流程--------How Android(安卓)D