美文网首页
Android动态设置控件的大小

Android动态设置控件的大小

作者: 因为我的心 | 来源:发表于2020-04-24 16:45 被阅读0次

一、前言:

在App开发中,我们经常要用到根据屏幕的宽高,设置控件的宽高,这样在手机端和平板端,不至于控件过小或者过大的情况,达到完美的适配。

支持父类是LinearLayout、RelativeLayout、ScrollView、RecyclerView等等,各种父类容器。

二、解决:

   ImageView image = findViewById(R.id.image);
            image.post(new Runnable() {
                @Override
                public void run() {
                    //自己获取屏幕的宽
                    int newWidth= ScreenUtils.getScreenWidth();
                    //获取自己控件的高度
                    int newHeight = image.getMeasuredHeight();
                    //取控件当前的布局参数
                    ViewGroup.LayoutParams params = image.getLayoutParams();
                    //设置宽度值
                    params.width = newWidth;
                    //设置高度值
                    params.height = newHeight;
                    //使设置好的布局参数应用到控件
                    image.setLayoutParams(params);
                }
            });

注意:

  • 控件可以是ImageView、TextView、LinearLayout、RelativeLayout任何控件;
  • 一定要在控件post方法的runnable中获取自己控件的高度,确保控件测量和布局完成;
  • image.getLayoutParams();获取该控件的布局参数;
  • image.setLayoutParams(params);设置布局参数即可;

相关文章

网友评论

      本文标题:Android动态设置控件的大小

      本文链接:https://www.haomeiwen.com/subject/cdgfwhtx.html