Android动态布局小结
android动态布局相比静态布局,动态布局不用再将xml转变了布局代码,提高了一定的效率,当然可以忽略不记。动态布局主要是比较灵活,可以很快的在代码中直接修改布局,并直接使用控件进行业务逻辑开发。但代码量通常比较大,维护没有静态布局方便。不过,作为一个android开发人员,掌握一定的动态布局技巧,有时在工作中也是可以提高一定的代码开发效率。
在动态布局中,要想实现一个布局,一般是先创建五大布局的对象。然后对这些对象进行属性设置,之后再向里面添加子布局或控件。
以RelativeLayout为例。
RelativeLayout mLayout = new RelativeLayout(); //设置RelativeLayout的子控件属性对象,并设置其尺寸样式。每个GroupView中都有一个LayoutPrams,都是用来给子控件设置发生的。 RelativeLayout.LayoutPrams params = new RelativeLayout.LayoutPrams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //增加 子控件 ImageView iv = new ImageView(getActivity()); iv.setImageResource(R.drawable.tab_icon_conversation_normal); //设置子控件在RealtiveLayout中的位置属性。 params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); //给iv 增加属性 //将iv,增加到mLayout中 mLayout .addView(iv, params);
从最后一句,可以看出来,params对象引用设置的属性都是作用有ImageView这个子控件上的,然后把iv与params一块加入到RealtiveLayout中去。
整理android动态布局方法总结
//绝对布局
AbsoluteLayout abslayout=new AbsoluteLayout (this); setContentView(abslayout); Button btn1 = new Button(this); btn1.setText(”this is a button”); btn1.setId(1); AbsoluteLayout.LayoutParams lp1 = new AbsoluteLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0,100); abslayout.addView(btn1, lp1);
//相对布局
RelativeLayout relativeLayout = new RelativeLayout(this); setContentView(relativeLayout); AbsoluteLayout abslayout=new AbsoluteLayout (this); RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP); lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE); relativeLayout.addView(abslayout ,lp1);
//线性布局
LinearLayout ll = new LinearLayout(this); EditText et = new EditText(); ll.addView(et); //动态添加布局的方法1. LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,ll); //这样 main2 作为 main1的子布局 加到了 main1的 根节点下 //动态添加布局的方法2 addView. LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,null); ll.addView(ll2);
相关文章
Android中ListView的item点击没有反应的解决方法
这篇文章主要介绍了Android中ListView的item点击没有反应的相关资料,需要的朋友可以参考下2017-10-10
android开发之蜂鸣提示音和震动提示的实现原理与参考代码
蜂鸣提示音和震动提示此功能在手机使用中很实用,最近在读zxing项目,学到了不少东西;我们一起来看看他是怎么做的,感兴趣的朋友可以了解下哦2013-01-01
Android使用观察者模式Observer实现网络状态监听
这篇文章主要为大家详细介绍了Android使用观察者模式Observer实现网络状态监听,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2018-05-05


最新评论