·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> Android动态布局小结

Android动态布局小结

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

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