2014-10-27 103 views
2

我試圖讓我給硬編碼邊距的textview的頂部和左邊緣。如何獲得TextView的邊距?

爲什麼我這麼做?因爲我想循環遍歷所有的textviews,所以我可以在這個textview中放置所以我可以編程在這些精確的邊界上添加單選按鈕組。

textView[0] = new TextView(context); 
relativeLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, 
RelativeLayout.LayoutParams.WRAP_CONTENT); 
textView[0].setId(1); // changed id from 0 to 1 
textView[0].setText(naam[0].toUpperCase()); 
relativeLayoutParams.setMargins(24, 39, 0, 0); 
int tyo = relativeLayoutParams.getTop(); //Trying to get top margins. 
+0

爲什麼不使用的LinearLayout和重量的魔力? – 2014-10-27 10:46:53

+0

你可以通過'getTop()'和'getLeft()'獲得'TextView'的位置。檢查此:http://developer.android.com/reference/android/view/View.html#getTop() – dreamcoder 2014-10-27 10:49:50

+0

任何具體的不工作?只是看到一堆代碼。 – Simas 2014-10-27 11:15:57

回答

4

那麼你可以簡單地以相反的方式。只需獲取佈局參數。

RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) textView.getLayoutParams(); 

然後,您可以通過全局變量訪問邊距。

lp.topMargin 
lp.leftMargin 
lp.bottomMargin 
lp.rightMargin 
0

試試這個

RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.WRAP_CONTENT, 
      RelativeLayout.LayoutParams.WRAP_CONTENT); 
    rl.addRule(RelativeLayout.CENTER_VERTICAL); 
    RelativeLayout.LayoutParams textParams; 
    textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
               LayoutParams.WRAP_CONTENT); 

    textParams.addRule(RelativeLayout.RIGHT_OF, id_of_left_content); 
    textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, id_of_top_content); 
    textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, id_of_bottom_content); 
    textParams.addRule(RelativeLayout.CENTER_VERTICAL); 

我希望這個概念將幫助您