設置TextView文字居中,代碼實現android:layout_gravity


設置TextView文字居中

android:gravity指的是控件的位置

而android:layout_gravity指的是這個layout的,是外面的

有2種方法可以設置TextView文字居中:
一:在xml文件設置:android:gravity="center"
二:在程序中設置:m_TxtTitle.setGravity(Gravity.CENTER);

備注:android:gravity和android:layout_gravity的區別在於前者對控件內部操作,后者是對整個控件操作。

例如:android:gravity="center"是對textView中文字居中
android:layout_gravity="center"是對textview控件在整個布局中居中
其實很容易理解,出現"layout"就是控件對整個布局的操作

 

設置TextView文字居中一般使用如下:

android:layout_width="fill_parent"              注意這里聲明要為match_parent
android:layout_height="fill_parent"
android:gravity="center"

 

代碼實現android:layout_gravity

通過查看SDK,發現有一個setGravity方法, 顧名思義, 這個應該就是用來設置Button組件中文字的對齊方式的方法了。
仔細找了一圈,沒有發現setLayoutgravity方法,有點失望。 不過想想也對,如果這邊有了這個方法,將Button放在不支持Layout_Gravity屬性的Container中如何是好!

代碼比較簡單,但是發現它們還是花了我一點時間的

Button button  = new Button(this);  
button.setText("One");  

//此處相當於布局文件中的Android:layout_gravity屬性  
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
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中的位置時使用addRule方法,如下:

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
params.addRule(RelativeLayout.CENTER_IN_PARENT);  
mContainer.addView(progress,params);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM