Resources resources = getResources();
float fPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, resources.getDisplayMetrics());
// 同理 px转dip:
// float fDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 300, resources.getDisplayMetrics());
// int iDip = Math.round(fDip);
int iPx = Math.round(fPx);
EditText editText = new EditText(this);
editText.setWidth(iPx);
editText.setHeight(LayoutParams.WRAP_CONTENT);
// 或者
// LayoutParams layoutParams = new LayoutParams(iPx, LayoutParams.WRAP_CONTENT);
// editText .setLayoutParams(layoutParams);
注:有时直接使用setWidth等不起作用,可以使用LayoutParams 设置。