//方式一
LayoutInflater layoutInflater = this.getLayoutInflater();
//方式二
LayoutInflater layoutInflater = LayoutInflater.from(this);
//方式三
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//布局管理器填充布局
View view = inflater.inflate(R.layout.demo, null, false);
//第一种写法
View view = View.inflate(this, R.layout.demo, null);
//第二种写法
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.demo, null, false);
//第三种写法
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.demo, null, false);
mTv4 = ((TextView) this.findViewById(R.id.tv4));
//获取布局参数(注意转化为父布局的布局参数)
layoutParam4 = ((LinearLayout.LayoutParams) mTv4.getLayoutParams());
//设置布局的宽度属性(这里使用系统设置尺寸的方法applyDimension)
layoutParam4.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
//设置布局参数
mTv4.setLayoutParams(layoutParam4);
或者
mTv2 = ((TextView) this.findViewById(R.id.tv2));
//获取布局参数(注意转化为父布局的布局参数)
layoutParam2 = ((LinearLayout.LayoutParams) mTv2.getLayoutParams());
//设置布局的宽度属性(这里使用自己写的dp转换px)
layoutParam2.width = (int) dipToPx(this, 300f);
//设置布局参数
mTv2.setLayoutParams(layoutParam2);
//dp转px
private float dipToPx(Context context, float dip) {
return dip * getDeviceDensity(context) + 0.5f;
}
//获取屏幕密度
private float getDeviceDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
//px转dp
private float pxToDip(Context context, float px) {
return px / getDeviceDensity(context) + 0.5f;
}
layoutParam4.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
public static float applyDimension(int unit, float value,
DisplayMetrics metrics)
{
switch (unit) {
case COMPLEX_UNIT_PX:
return value;
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}
和一般自己定义
layoutParam2.width = (int) dipToPx(this, 300f);
//dp转px
private float dipToPx(Context context, float dip) {
return dip * getDeviceDensity(context) + 0.5f;
}
比较发现多了0.5f,但是获得的结果都是相同的。
注意:float转换为int是直接去掉小数