2014-10-27 104 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); 

我希望这个概念将帮助您