2011-01-27 76 views
7

如果我只爲我的textview設置了邊距,那是在線性佈局內,一切正常。 如果我只爲我的textview設置重力,它會起作用。但是,如果我設置了兩個屬性(重力和邊距),重力仍保持成功設置邊距。在代碼中設置textview的邊距和重力不起作用

我的設置是不工作按預期這兩個屬性代碼:

tv2=new TextView(this); 
tv2.setText("Text"); 
LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
para.setMargins(0, 10, 0, 10); //left,top,right, bottom 
tv2.setLayoutParams(para); 
tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL); 

我必須在代碼中建立自己的佈局,不能使用XML文件。

回答

14

嘗試使用這個:

para.gravity = Gravity.CENTER_HORIZONTAL; 
tv2.setLayoutParams(para); 

//the below sets the view's content gravity, not the gravity 
//of the view itself. Since the width is wrap_content, this 
//has no effect. 
//tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL); 
+0

很不錯的傢伙... – Siten 2011-12-02 06:02:27