android 动态设置屏幕控件宽高度

来源:互联网 发布:下载办公软件wpsoffice 编辑:程序博客网 时间:2024/05/21 13:57

获取屏幕宽高度:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(outMetrics);
outMetrics.widthPixels
outMetrics.heightPixels

 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);
为什么需要这么麻烦呢,有时候xml不能满足现状的需求

设置控件的宽高度:

先还是要获取屏幕的宽高度

imageView=(ImageView)findViewById(R.id.imageView1);//获取当前控件的对象LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) imageView.getLayoutParams();//获取当前控件的布局对象params.height=width/2;//设置当前控件布局的高度width是屏幕宽度imageView.setLayoutParams(params);//将设置好的布局参数应用到控件中
这里把imageview看做是linearlayout的子视图

不一定是LinearLayout也可以是其他relativelayout也可以的


推荐:http://blog.csdn.net/Djoli/article/details/62417328

http://blog.csdn.net/James_shu/article/details/53363234



 
原创粉丝点击