標籤:
在進行UI布局的時候,可能常常會用到 android:gravity 和 android:layout_Gravity 這兩個屬性。
關於這兩個屬性的差別,網上已經有許多人進行了說明,這邊再簡單說一下。 (資料來自網路)
LinearLayout有兩個很類似的屬性:
android:gravity與android:layout_gravity。
他們的差別在於:
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的對齊。
原理跟android:paddingLeft、android:layout_marginLeft有點類似。假設在按鈕上同一時候設定這兩個屬性。
android:paddingLeft="30px" 按鈕上設定的內容離按鈕左邊邊界30個像素
android:layout_marginLeft="30px" 整個按鈕離左邊設定的內容30個像素
以下回到正題, 我們能夠通過設定android:gravity="center"來讓EditText中的文字在EditText組件中置中顯示;同一時候我們設定EditText的android:layout_gravity="right"來讓EditText組件在LinearLayout中居右顯示。看下效果:
正如我們所示,在EditText中,當中的文字已經置中顯示了,而EditText組件自己也對齊到了LinearLayout的右側。
附上布局檔案:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:layout_width="wrap_content" android:gravity="center" android:layout_height="wrap_content" android:text="one" android:layout_gravity="right"/></LinearLayout>
那麼上面是通過布局檔案的方式來設定的。,相信大家都曾寫過,那麼怎樣通過Java代碼來設定組件的位置呢?
依舊考慮實現上述效果。
通過查看SDK,發現有一個setGravity方法, 顧名思義, 這個應該就是用來設定Button組件中文字的對齊的方法了。
細緻找了一圈,沒有發現setLayoutgravity方法, 有點失望。 只是想想也對, 假設這邊有了這種方法, 將Button放在不支援Layout_Gravity屬性的Container中怎樣是好!
於是想到, 這個屬性有可能在Layout中 , 於是細緻看了看LinearLayout 的 LayoutParams, 果然有所發現, 裡面有一個 gravity 屬性,相信這個就是用來設定組件相對於容器本身的位置了,沒錯,應該就是他了。
實踐後發現,假設如此, 附上代碼,各位自己看下。
代碼比較簡單,可是發現它們還是花了我一點時間的。
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);
或者這樣也能夠:
Button button = new Button(this);button.setText("One");//此處相當於布局檔案裡的Android:gravity屬性button.setGravity(Gravity.CENTER);LinearLayout linear = new LinearLayout(this);//注意,對於LinearLayout布局來說,設定橫向還是縱向是必須的!否則就看不到效果了。linear.setOrientation(LinearLayout.VERTICAL);LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);//此處相當於布局檔案裡的Android:layout_gravity屬性lp.gravity = Gravity.RIGHT;linear.addView(button, lp);setContentView(linear);
好了,就不上了,跟上面的一樣。 就講這麼多。
另外,要設定在RelativeLayout中的位置時使用addRule方法,例如以下:
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.CENTER_IN_PARENT); mContainer.addView(progress,params);
假設認為本文對您有協助, 還請留言支援一下, 很感謝!
【Android布局】在程式中設定android:gravity 和 android:layout_Gravity屬性