获取屏幕宽高度:
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
outMetrics.widthPixels
outMetrics.heightPixels
为什么需要这么麻烦呢,有时候xml不能满足现状的需求LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear1);//找到xml上的控件 LinearLayout linearLayout2 = (LinearLayout) findViewById(R.id.linear3);//找到xml上的控件 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(widths,DensityUtils.dp2px(context,40));//设置控件的宽高 ImageView imageView = new ImageView(context);//动态添加imageview控件 imageView.setBackground(getResources().getDrawable(R.mipmap.shishi_lefttup));//设置背景图片 ImageView imageview2 = new ImageView(context); imageview2.setBackground(getResources().getDrawable(R.mipmap.shishi_rightup)); linearLayout.addView(imageView,params);//把控件添加到LinearLayout里面去 linearLayout2.addView(imageview2,params);
设置控件的宽高度:
先还是要获取屏幕的宽高度
这里把imageview看做是linearlayout的子视图imageView=(ImageView)findViewById(R.id.imageView1);//获取当前控件的对象 LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) imageView.getLayoutParams(); //获取当前控件的布局对象 params.height=width/2;//设置当前控件布局的高度width是屏幕宽度 imageView.setLayoutParams(params);//将设置好的布局参数应用到控件中
不一定是LinearLayout也可以是其他relativelayout也可以的
推荐:http://blog.csdn.net/Djoli/article/details/62417328
http://blog.csdn.net/James_shu/article/details/53363234