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);

更多相关文章

  1. 你真的了解android:layout_weight吗?
  2. 搜集整理的一些博客导航
  3. Android深入浅出自定义控件(三)
  4. 重拾Android之路(三)手机适配
  5. Android布局管理器总结一:LinearLayout
  6. 【Android】实现桌面清理内存简单Widget小控件
  7. Fragment的快速入门
  8. Android实验5---通讯录(解决ListView刷新问题及一些编码规范的总
  9. Android(安卓)RecyclerView和ListView多布局实现

随机推荐

  1. Android的Service总结
  2. Android(安卓)命名规范 (提高代码可以读性
  3. Programming 3D games on Android with I
  4. android高效编程之使用本地变量
  5. 【Android】OpenGL ES for Android 教程1
  6. 看Android 應用框架原理與程式設計36 技有
  7. Android AIDL 实例
  8. Android 图片预览模仿朋友圈查看图片效果
  9. mac电脑开发android找不到设备
  10. android TraceView (图形化性能测试工具)