如何以编程方式在dp中设置EditText TopMargins? [英] how to set EditText TopMargins in dp programatically?

查看:45
本文介绍了如何以编程方式在dp中设置EditText TopMargins?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my android application I want to change the topMargin of an editText.

问题是我想将其改为"dp"而不是像素.

The thing is that I want to change it "dp" wise and not pixel wise.

我只想更改topMaring.保持原样.不是将它们设置为零?

I want to change only the topMaring. Leave the other as is. not set them to zeros ?

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

programmatically i can set margins in int only?

推荐答案

设置如下代码:

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);

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;
}

使用以下代码仅更改其中一个.

use follow code for changing just one.

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.topMargin = convertPixelsToDp(5,this);
    editText.setLayoutParams(params);

这篇关于如何以编程方式在dp中设置EditText TopMargins?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆