简体   繁体   English

如何在xml中改变java中textview的位置

[英]How to change postion of textview in java the way i would in xml

in xml my textview looks like this. 在xml中,我的textview看起来像这样。

` `

     android:layout_marginTop="248dp"
     android:text="hello world"
     android:textColor="#646464"
     android:textSize="200sp"
     android:textStyle="bold" />`

when i want to move my textview left or right i edit the value in the marginleft parameter and if i want to move my textview up or down i edit the margin top value. 当我想向左或向右移动我的textview我编辑marginleft参数中的值,如果我想向上或向下移动我的textview我编辑边缘顶部值。 I want to be able to have this sort of control over the textview positioning in java. 我希望能够对java中的textview定位进行这种控制。 Can someone show me an example of code of this being done maybe using my textview as an example and moving the textview so that its new margin left is 160? 有人可以给我看一个这样做的代码示例,也许可以使用我的textview作为示例并移动textview以使其新的边距为160?

See here 看到这里

Create a layout param and set the margins ie layoutParams.setMargins(160,0,0,0); 创建布局参数并设置边距即layoutParams.setMargins(160,0,0,0);

if you want to change the margin ( in dp ) of your TextView programmatically, try this ( change the values of left, top, right , bottom with the value that you want to set as margin ): 如果要以编程方式更改TextView的边距(以dp为单位) ,请尝试此操作(使用要设置为边距的值更改left,top,right,bottom的值):

float density = getResources().getDisplayMetrics().density;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) textView.getLayoutParams();
params.setMargins(left * density, top * density, right * density, bottom * density);
textView.setLayoutParams(params);

You can change TextView's LayoutParams programatically as follows: 您可以按编程方式更改TextView的LayoutParams,如下所示:

TextView textView = /* your textview here ... */;
LinearLayout.LayoutParams lparam = 
       new LinearLayout.LayoutParams(textView.getLayoutParams());
lparam.topMargin = /* ... */;
lparam.rightMargin = /* ... */;
// or use lparam.setMargins() method.
textView.setLayoutParams(p);
TextView tv =(TextView)findViewById(R.id.id of textview in xml);

 tv.setPadding(15, 0, 0, 0);
//tv.setPadding(left, top, right, bottom);
 tv.setText( "Work");
 tv.setTextSize(17);
 tv.setTextColor(Color.parseColor("#000000"));

You can do this in java code. 您可以在java代码中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM