안드로이드 레이아웃 파라미터 소스에서 설정하기 예제 (setLayoutParams) 및 pixel 과 dp 변환


	
   RelativeLayout.LayoutParams params =  new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   params.setMargins(Utilities.getDpToPixel(MainActivity.this, 70), 0, 0, 0);
   tvTitle.setLayoutParams(params);


Utilities 클래스

public class Utilities {
	public static int getPixelToDp(Context context, int pixel) {
		float dp = 0;
		try {
			DisplayMetrics metrics = context.getResources().getDisplayMetrics();
			dp = pixel / (metrics.densityDpi / 160f);
		} catch (Exception e) {
			
		}
		return (int) dp;
	}

	public static int getDpToPixel(Context context, int DP) {
		float px = 0;
		try {
			px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
		} catch (Exception e) {
			
		}
		return (int) px;
	}

	public static int getDpToPixel(Context context, float DP) {
		float px = 0;
		try {
			px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
		} catch (Exception e) {
			
		}
		return (int) px;
	}
}


+ Recent posts