android layout_gravity 和gravity

LinearLayout有兩個很是類似的屬性: java

android:gravity與android:layout_gravity。(RelativeLayout是沒有android:layout_gravity屬性的) android

他們的區別在於:
android:gravity 屬性是對該view中內容的限定.好比一個button 上面的text. 你能夠設置該text 相對於view的靠左,靠右等位置.(文本圖片等)


android:layout_gravity是用來設置該view相對與父view 的位置.好比一個button 在linearlayout裏,你想把該button放在linearlayout裏靠左、靠右等位置就能夠經過該屬性設置. 
 
即android:gravity用於設置View中內容相對於View組件的對齊方式,而android:layout_gravity用於設置View組件相對於Container的對齊方式。
佈局

代碼實現: this

查看SDK發現有一個setGravity方法, 顧名思義, 這個應該就是用來設置Button組件中文字的對齊方式的方法了 spa

LinearLayout 的 LayoutParams, 果真有所發現, 裏面有一個 gravity 屬性,相信這個就是用來設置組件相對於容器自己的位置了 code

Button button  = new Button(this);  
button.setText("One");  
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
//此處至關於佈局文件中的Android:layout_gravity屬性  
lp.gravity = Gravity.RIGHT;  
button.setLayoutParams(lp);  
//此處至關於佈局文件中的Android:gravity屬性  
button.setGravity(Gravity.CENTER);  
  
LinearLayout linear = new LinearLayout(this);  
//注意,對於LinearLayout佈局來講,設置橫向仍是縱向是必須的!不然就看不到效果了。  
linear.setOrientation(LinearLayout.VERTICAL);  
linear.addView(button);  
setContentView(linear);
在RelativeLayout設置gravity屬性

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
        params.addRule(RelativeLayout.CENTER_IN_PARENT);  
        mContainer.addView(progress,params);
相關文章
相關標籤/搜索