如何以编程方式在dp中设置EditText TopMargins?

Ela*_*da2 8 layout android margin android-layout

在我的Android应用程序中,我想更改editText的topMargin.

问题是我想改变它"dp"明智而不是像素化.

我想只改变topMaring.保持原样.不把它们设置为零?

以编程方式我只能在int中设置边距?

Sha*_*tan 9

像follw代码一样设置:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, convertPixelsToDp(5,this), 0, 0);
editText.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)

convert Pixels To Dp

public static int convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    int dp = px / (metrics.densityDpi / 160f);
    return dp;
}
Run Code Online (Sandbox Code Playgroud)

使用follow代码只更改一个.

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.topMargin = convertPixelsToDp(5,this);
    editText.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)