android : 控件在代码中设置属性-setWidth(int pixels)或setHeight(int pixels)的px与dip转换

 

---------------------------------------华丽的分割线-----------------------------------------

  

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 设置。

 

你可能感兴趣的:(android)