Android:以编程方式设置textview的一个填充

时间:2022-11-25 14:08:29

I want to set the top padding of a textview programmatically. I know you can do this with the method setPadding(). But the problem is that this method requires 4 parameters: left, top, right, bottom. I don't want to change the left, right and bottom, I just want to change the top padding.

我想以编程方式设置textview的顶部填充。我知道你可以用方法setPadding()来做到这一点。但问题是这种方法需要4个参数:左,上,右,下。我不想改变左,右和底,我只是想改变顶部填充。

Is that possible?

那可能吗?

2 个解决方案

#1


57  

use

使用

    yourTextView.setPadding(0, 10, 0, 0);

Adjust only the parameters you need and set the other ones to zero.

仅调整所需的参数,并将其他参数设置为零。

If you need to preserve other existing paddings, use yourView.getPaddingLeft(), yourView.getPaddingTop() and so on.

如果需要保留其他现有的填充,请使用yourView.getPaddingLeft(),yourView.getPaddingTop()等。

#2


15  

I usually create a simple utility method just to not forget, or misplace the other paddings:

我通常创建一个简单的实用工具方法,只是为了不忘记或错放其他填充:

public static void setPaddingLeft(View v, int leftPaddingDp) {
    int leftPaddingPx = dpToPx(leftPaddingDp);
    v.setPadding(leftPaddingPx, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());
}

To be used later like this, supplying dp units, as if would in xmls:

要像以后一样使用,提供dp单位,就像在xmls中一样:

Utils.setPaddingLeft(myExampleTextView, 10)

#1


57  

use

使用

    yourTextView.setPadding(0, 10, 0, 0);

Adjust only the parameters you need and set the other ones to zero.

仅调整所需的参数,并将其他参数设置为零。

If you need to preserve other existing paddings, use yourView.getPaddingLeft(), yourView.getPaddingTop() and so on.

如果需要保留其他现有的填充,请使用yourView.getPaddingLeft(),yourView.getPaddingTop()等。

#2


15  

I usually create a simple utility method just to not forget, or misplace the other paddings:

我通常创建一个简单的实用工具方法,只是为了不忘记或错放其他填充:

public static void setPaddingLeft(View v, int leftPaddingDp) {
    int leftPaddingPx = dpToPx(leftPaddingDp);
    v.setPadding(leftPaddingPx, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());
}

To be used later like this, supplying dp units, as if would in xmls:

要像以后一样使用,提供dp单位,就像在xmls中一样:

Utils.setPaddingLeft(myExampleTextView, 10)