Android动态布局小结
android动态布局相比静态布局,动态布局不用再将xml转变了布局代码,提高了一定的效率,当然可以忽略不记。动态布局主要是比较灵活,可以很快的在代码中直接修改布局,并直接使用控件进行业务逻辑开发。但代码量通常比较大,维护没有静态布局方便。不过,作为一个android开发人员,掌握一定的动态布局技巧,有时在工作中也是可以提高一定的代码开发效率。
在动态布局中,要想实现一个布局,一般是先创建五大布局的对象。然后对这些对象进行属性设置,之后再向里面添加子布局或控件。
以RelativeLayout为例。
RelativeLayoutmLayout=newRelativeLayout(); //设置RelativeLayout的子控件属性对象,并设置其尺寸样式。每个GroupView中都有一个LayoutPrams,都是用来给子控件设置发生的。 RelativeLayout.LayoutPramsparams=newRelativeLayout.LayoutPrams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //增加子控件 ImageViewiv=newImageView(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动态布局方法总结
//绝对布局
AbsoluteLayoutabslayout=newAbsoluteLayout(this); setContentView(abslayout); Buttonbtn1=newButton(this); btn1.setText(”thisisabutton”); btn1.setId(1); AbsoluteLayout.LayoutParamslp1= newAbsoluteLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0,100); abslayout.addView(btn1,lp1);
//相对布局
RelativeLayoutrelativeLayout=newRelativeLayout(this); setContentView(relativeLayout); AbsoluteLayoutabslayout=newAbsoluteLayout(this); RelativeLayout.LayoutParamslp1=newRelativeLayout.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);
//线性布局
LinearLayoutll=newLinearLayout(this); EditTextet=newEditText(); ll.addView(et); //动态添加布局的方法1.LinearLayoutll=(LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);setContentView(ll);LinearLayoutll2=(LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,ll);//这样main2作为main1的子布局加到了main1的根节点下 //动态添加布局的方法2addView.LinearLayoutll=(LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);setContentView(ll);LinearLayoutll2=(LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,null);ll.addView(ll2);