Android動態(tài)布局小結
android動態(tài)布局相比靜態(tài)布局,動態(tài)布局不用再將xml轉變了布局代碼,提高了一定的效率,當然可以忽略不記。動態(tài)布局主要是比較靈活,可以很快的在代碼中直接修改布局,并直接使用控件進行業(yè)務邏輯開發(fā)。但代碼量通常比較大,維護沒有靜態(tài)布局方便。不過,作為一個android開發(fā)人員,掌握一定的動態(tài)布局技巧,有時在工作中也是可以提高一定的代碼開發(fā)效率。
在動態(tài)布局中,要想實現(xiàn)一個布局,一般是先創(chuàng)建五大布局的對象。然后對這些對象進行屬性設置,之后再向里面添加子布局或控件。
以RelativeLayout為例。
RelativeLayout mLayout = new RelativeLayout(); //設置RelativeLayout的子控件屬性對象,并設置其尺寸樣式。每個GroupView中都有一個LayoutPrams,都是用來給子控件設置發(fā)生的。 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動態(tài)布局方法總結
//絕對布局
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); //動態(tài)添加布局的方法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的 根節(jié)點下 //動態(tài)添加布局的方法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編程實現(xiàn)TextView部分顏色變動的方法
這篇文章主要介紹了Android編程實現(xiàn)TextView部分顏色變動的方法,涉及Android針對TextView樣式操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11Android之高德地圖定位SDK集成及地圖功能實現(xiàn)
本文主要介紹了Android中高德地圖定位SDK集成及地圖功能的實現(xiàn)。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04Flutter輸入框TextField屬性及監(jiān)聽事件介紹
這篇文章主要介紹了Flutter輸入框TextField屬性及監(jiān)聽事件介紹,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-11-11Android啟動初始化方案App StartUp的應用詳解
這篇文章主要介紹了Android啟動初始化方案App StartUp的使用方法,StartUp是為了App的啟動提供的一套簡單、高效的初始化方案,下面我們來詳細了解2022-09-09