安卓LayoutParams浅析

目录

  • 前言
  • 一、使用 LayoutParams 设置宽高
  • 二、不设置 LayoutParams
    • 2.1 TextView 的 LayoutParams
    • 2.2 LinearLayout 的 LayoutParams
  • 三、getLayoutParams 的使用
  • 四、setLayoutParams 的作用
  • 五、使用 setWidth/setHeight 设置宽高


前言

先来看一个简单的布局,先用 xml 写

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00F5FF"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="160dp"
        android:layout_height="160dp"
        android:background="#FFFACD"
        android:text="12345678" />

</LinearLayout>

效果也很简单:
在这里插入图片描述

如果想要代码动态写出上面的布局,就需要使用 LayoutParams 这个关键类了,
LayoutParams 是 ViewGroup 的一个内部类,这是一个基类,例如 FrameLayout、LinearLayout 等等,内部都有自己的 LayoutParams。

一、使用 LayoutParams 设置宽高

LayoutParams 的作用是: 子控件告诉父控件,自己要如何布局。

代码实现:

public class LayoutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LinearLayout ll = new LinearLayout(getContext());
//11的父容器是MainActivity中的FrameLayout
        ll.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ll.setGravity(Gravity.CENTER);
        ll.setBackgroundColor(Color.BLUE);
        TextView tv = new TextView(getContext());
//tv的父容器是LinearLayout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(160, 160);
        tv.setLayoutParams(layoutParams);//
        tv.setBackgroundColor(Color.RED);
        tv.setText("123145678");
        ll.addView(tv);// c
        return ll;
    }
}

我们对 LinearLayout 和 TextView 的 LayoutParams 都进行了设置,效果图和上面 xml的是一模一样的。
ll.setLayoutParams 设置的是其父布局 FrameLayout 的 LayoutParams,并且告诉父布局,宽高设置为 MATCH_PARENT。
tv.setLayoutParams 设置的也是其父布局 LinearLayout 的 LayoutParams,并且告诉父布局,宽高设置为 160dp。
上面 ①、 ② 两行代码可以简化为一行,替换为 addView(View child, LayoutParamsparams) 这个重载方法,在添加到父布局时,设置 LayoutParams,通知父布局如何摆放自己。
ll.addView(tv, layoutParams);// 子布局添加到父布局


二、不设置 LayoutParams

public class LayoutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LinearLayout ll = new LinearLayout(getContext());
        ll.setGravity(Gravity.CENTER);
        ll.setBackgroundColor(Color.BLUE);
        TextView tv = new TextView(getContext());
//tv的父容器是LinearLayout

        tv.setBackgroundColor(Color.RED);
        tv.setText("123145678");
        ll.addView(tv);// c
        return ll;
    }
}
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "henry-----";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        LayoutFragment fragment = new LayoutFragment();
        transaction.add(R.id.test, fragment);
        transaction.commit();
    }

}

效果如下:
在这里插入图片描述
发现在对 LinearLayout 和 TextView 的 都不设置 LayoutParams 的情况下,LinearLayout 使用 MATCH_PARENT,而 TextView 使用 WRAP_CONTENT,至于为什么,要分析一下源码

2.1 TextView 的 LayoutParams

进入 addView 看一下,不存在 LayoutParams 时,会调用generateDefaultLayoutParams() 进行创建。

    public void addView(View child, int index) {
        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }
        LayoutParams params = child.getLayoutParams();
        if (params == null) {
            params = generateDefaultLayoutParams();
            if (params == null) {
                throw new IllegalArgumentException(
                        "generateDefaultLayoutParams() cannot return null  ");
            }
        }
        addView(child, index, params);
    }

找到 LinearLayout 中 generateDefaultLayoutParams(),注意不是 ViewGroup 中的

    protected LayoutParams generateDefaultLayoutParams() {
        if (mOrientation == HORIZONTAL) {
            return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        } else if (mOrientation == VERTICAL) {
            return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }
        return null;
    }

显而易见,由于我们没有指定方向, mOrientation 默认为 0,也就是 HORIZONTAL,所以 TextView 设置为
WRAP_CONTENT,为了证实猜想,我们设置 LinearLayout 的方向为 VERTICAL。

        ll.setOrientation(LinearLayout.VERTICAL);

效果跟代码看到的一样,宽度为 MATCH_PARENT,高度为WRAP_CONTENT:
在这里插入图片描述

2.2 LinearLayout 的 LayoutParams

和上面 TextView 一样,这个要进入 FrameLayout 中查看 generateDefaultLayoutParams()。

    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

所以,在 FrameLayout 中的 LinearLayout 的宽高就是 MATCH_PARENT。


三、getLayoutParams 的使用

在不使用代码动态布局的情况下,大都是先通过 getLayoutParams() 获取LayoutParams ,然后进行赋值,最后通过 setLayoutParams()设回控件,值得注意的是,获取 LayoutParams 务必要强转为父控件的类型,才会有该父控件特有的方法。

public class LayoutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayout
        FrameLayout.LayoutParams fl_params = (FrameLayout.LayoutParams)
                ll.getLayoutParams();// ①
        fl_params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        fl_params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        ll.setLayoutParams(fl_params);
        ll.setGravity(Gravity.CENTER);
        ll.setBackgroundResource(android.R.color.holo_blue_bright);
        TextView tv = new TextView(getContext());
// tv 的父容器是 LinearLayout
        LinearLayout.LayoutParams ll_params = (LinearLayout.LayoutParams)
                tv.getLayoutParams();// ②
        ll_params.width = 160;
        ll_params.height = 160;
        tv.setLayoutParams(ll_params);tv.setBackgroundResource(android.R.color.holo_red_dark);
        tv.setText("12345678");
        ll.addView(tv);
        return ll;

    }
}

运行报错:
在这里插入图片描述

上面代码是有问题的, ①、 ②处都会返回 null,导致空指针。
①处:此时还没有将 LinearLayout 作为返回值返回,也就没有添加到布局中,自然不存
在 LayoutParams。
②处:此时还没有将 TextView 添加到 LinearLayout 中,也不存在 LayoutParams。
下面才是正确的示例:

public class LayoutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayout
        ll.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ll.setGravity(Gravity.CENTER);// 子控件居中
        ll.setBackgroundResource(android.R.color.holo_blue_bright);
        TextView tv = new TextView(getContext());
        ll.addView(tv);// 添加到父控件,此时会构造一个 LayoutParams 出来。
        LinearLayout.LayoutParams ll_params = (LinearLayout.LayoutParams)
                tv.getLayoutParams();
        ll_params.width = 160;
        ll_params.height = 160;
        tv.setLayoutParams(ll_params);
        tv.setBackgroundResource(android.R.color.holo_red_dark);
        tv.setText("12345678");
        return ll;
    }
}

四、setLayoutParams 的作用

这里抛出一个问题:
上面代码中 getLayoutParams() 得到了 LayoutParams 的引用 ll_params,直接对width 和 height 属性赋值,那么 setLayoutParams() 是不是不需要调用了?
这就需要看看 setLayoutParams() 里面干了什么

    public void setLayoutParams(ViewGroup.LayoutParams params) {
        if (params == null) {
            throw new NullPointerException("Layout parameters cannot be null");
        }
        mLayoutParams = params;
        resolveLayoutParams();
        if (mParent instanceof ViewGroup) {
            ((ViewGroup) mParent).onSetLayoutParams(this, params);
        }
        requestLayout();
    }

关键的最后一行 requestLayout() ,这个方法简单来说,就是重新执行 onMeasure() 和onLayout(),而 onDraw() 需要适情况而定,这里就不具体展开说了。
现在就可以回答上面的问题了,在上面 onCreateView() 中的 setLayoutParams() 确实是多余的,因为在 onCreateView() 之后才会进行 View 的绘制。
当然这并不是说 setLayoutParams() 没有用,在自定义控件中,往往需要在 View 绘制后修改 LayoutParams 的值,那么这种场景下,如果不调用 setLayoutParams() 就会出现设置不生效的问题。
总结:

  • 在 LayoutParams 赋值后,如果确定还没有完成 View 的绘制,可以省略setLayoutParams() ,在后面绘制期间,会取到前面的赋值,并使之生效。
  • 如果已经完成了 View 的绘制,那么必须要调用setLayoutParams() ,重新进行绘制。
  • 不确定的情况下就setLayoutParams() ,反正不会出问题。

五、使用 setWidth/setHeight 设置宽高

在设置控件宽高时,有些人为了方便,没有使用 LayoutParams ,直接通过 set 方法设置,
但这种方式并不靠谱!

对 TextView 和 Button 分别设置宽高为 160px

public class LayoutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayout
        ll.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ll.setGravity(Gravity.CENTER);// 子控件居中
        ll.setBackgroundResource(android.R.color.holo_blue_bright);
        TextView tv = new TextView(getContext());
        tv.setWidth(160);
        tv.setHeight(160);
        tv.setBackgroundResource(android.R.color.holo_red_dark);
        tv.setText("12345678");
        ll.addView(tv);
        Button bt = new Button(getContext());
        bt.setWidth(160);
        bt.setHeight(160);
        bt.setBackgroundResource(android.R.color.holo_green_dark);
        bt.setText("12345678");
        ll.addView(bt);
        return ll;
    }
}

TextView 设置宽高成功, Button 只在高度上生效,效果如下:

在这里插入图片描述

可以打印下控件宽高看下结果:
在这里插入图片描述

Button 也是继承 TextView,为什么会出现设置失效?进入 setWidth 方法,看到在这里只是设置了控件的最大值和最小值:

    public void setWidth(int pixels) {
        mMaxWidth = mMinWidth = pixels;
        mMaxWidthMode = mMinWidthMode = PIXELS;

        requestLayout();
        invalidate();
    }

LayoutParams 设置的宽高才是真正的宽高:

在这里插入图片描述

再看下 onMeasure 中,这里面设置 width 时,有很多类似下面判断:
在这里插入图片描述

所以 setWidth()/setHeight 只代表想设置的宽高,并不是实际设定值。这就很好理解,
当 set 的值大于 Button 最小宽度/高度时生效,在小于 Button 最小宽度/高度时,不能起到作用。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/603404.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

百元挂耳式耳机哪款好?五款高品质一流机型不容错过

开放式耳机以其独特的不入耳设计&#xff0c;大大提升了佩戴的舒适度。相较于传统的入耳式耳机&#xff0c;它巧妙地避免了对耳朵的压迫&#xff0c;降低了中耳炎等潜在风险。不仅如此&#xff0c;开放式耳机还能让你保持对周边声音的灵敏度&#xff0c;无论是户外跑步还是骑行…

Day08-JavaWeb开发-MySQL(多表查询内外连接子查询事务索引)Mybatis入门

1. MySQL多表查询 1.1 概述 1.2 内连接 -- 内连接 -- A. 查询员工的姓名, 及所属的部门名称(隐式内连接实现) select tb_emp.name, tb_dept.name from tb_emp,tb_dept where tb_emp.dept_id tb_dept.id;-- 起别名 select * from tb_emp e, tb_dept d where e.dept_id d.id…

信息化飞速发展下,源代码防泄密方案该如何选择?常见四种有效方案分享

信息化时代发展迅速&#xff0c;数据防泄露一词也频繁的出现在我们身边。无论企业或政府单位&#xff0c;无纸化办公场景越来越多&#xff0c;数据泄露的时间也层出不穷。例如&#xff1a;世界最大职业中介网站Monster遭到黑客大规模攻击&#xff0c;黑客窃取在网站注册的数百万…

The Sandbox 案例|Web3 项目引领娱乐业的发展

Web3 如何通过 RZR 系列等项目开创娱乐新纪元。 我们已经看到技术和 Web3 如何颠覆金融和银行等行业&#xff0c;然而娱乐业在不断变化的环境中似乎发展滞后。传统的制片厂生态系统、高成本制作以及历史悠久的运作模式一直占据主导地位&#xff0c;而 Web3 项目的出现为创作者提…

CondaHTTPError: HTTP 404 NOT FOUND for url xxx

今天在创建新环境的时候给我报这个错 根据报错内容大概猜测&#xff0c;连接不到清华源&#xff1f; 然后我去清华源那边重新复制了一下配置 点这里跳转清华源 复制这一块东西 然后打开C盘->用户->找到.condarc文件打开 复制粘贴把里面的东西覆盖了就行 然后保存退出…

【excel】统计单元格内数字/字符串的数量

文章目录 一、问题二、步骤&#xff08;一&#xff09;将A1中的数字分解出来&#xff0c;在不同的单元格中显示&#xff08;二&#xff09;统计每个数字出现的个数&#xff08;三&#xff09;去重 三、尾巴 一、问题 单元格中有如下数值&#xff1a;12345234534545&#xff0c…

给excel中某列数值前后分别添加单引号

将这一列的数值&#xff0c;复制到 Sublime Text中&#xff0c;并CtrlA全选内容后&#xff0c;按CtrlH 选中工具栏左上角的 如果要给前面添加符号&#xff08;如单引号&#xff09;&#xff0c;则在Fina查找内容中&#xff0c;填入 ^ 如果要给后面添加符号&#xff08;如单引…

【操作系统】内存管理——地址空间连续内存分配与非连续内存分配

内存管理——地址空间&连续内存分配与非连续内存分配 一、地址空间1.1 计算机存储层次1.2 地址和地址空间1.3 虚拟存储的作用 二、内存分配2.1 静态内存分配2.2 动态内存分配 三、连续内存分配3.1 动态分区分配3.2 伙伴系统&#xff08;Buddy System&#xff09; 四、非连续…

5.1 Java全栈开发前端+后端(全栈工程师进阶之路)-服务端框架-MyBatis框架-相信我看这一篇足够

0.软件框架技术简介 软件框架&#xff08;software framework&#xff09;&#xff0c;通常指的是为了实现某个业界标准或完成特定基本任务的软件组件规范&#xff0c;也 指为了实现某个软件组件规范时&#xff0c;提供规范所要求之基础功能的软件产品。 框架的功能类似于基础设…

cufftPlanMany参数说明

背景 最近在看cufft这个库&#xff0c;传统的cufftPlan3d()这种plan接口逐渐被nvidia舍弃了&#xff0c;说是要用最新的cufftPlanMany&#xff0c;这个函数呢又依赖一个什么Advanced Data Layout(地址)&#xff0c;最终把这个api搞得乌烟瘴气很难理解&#xff0c;为了理解自己…

瓷器三维虚拟展示编辑平台为您量身定制高效实惠的展示方案

在竞争激烈的机械产品行业中&#xff0c;如何脱颖而出、展现产品魅力与企业实力?深圳vr公司华锐视点以其独特的三维动画设计制作服务&#xff0c;为您量身定制全方位的展示方案&#xff0c;让您的机械产品在市场中熠熠生辉。 全方位展示&#xff0c;细节尽收眼底 我们的三维展…

医学论文摘要翻译 中译英哪里比较专业

论文摘要是对论文内容不加注释和评论的简短陈述&#xff0c;需要扼要说明论文的目的、研究方法和最终结论。在发表学术论文时&#xff0c;很多重要刊物会要求作者将文章的摘要翻译成英文。那么&#xff0c;针对医学论文摘要翻译&#xff0c;中译英哪里比较专业&#xff1f; 专…

【论文速读】|针对模糊驱动生成的提示性模糊测试

本次分享论文&#xff1a;Prompt Fuzzing for Fuzz Driver Generation 基本信息 原文作者&#xff1a;Yunlong Lyu, Yuxuan Xie, Peng Chen, Hao Chen 作者单位&#xff1a;腾讯安全大数据实验室、加州大学戴维斯分校 关键词&#xff1a;软件测试, Fuzzing, 自动化Fuzz驱动…

Linux的基础IO:文件系统

目录 学前补充 磁盘的存储结构 OS如何对磁盘的存储进行逻辑抽象 细节内容 文件的增删改查 学前补充 问题&#xff1a;计算机只认二进制&#xff0c;即0、1&#xff0c;什么是0、1&#xff1f; 解释&#xff1a;0、1在物理层面可能有不同的表现&#xff0c;0、1是数字逻辑…

粘土制作的梵高世界;实时自由地转换您的声音Supertone;几秒钟内设计出令人惊叹的LOGO

✨ 1: 梵高的世界 你探索 runwayml #Gen2 过 的风格功能吗&#xff1f;看看这个用粘土制作的梵高作品的视频——就像走进了梵高的双手雕刻的世界。 &#x1f3a8; &#x1f58c;️ 关注更多将经典艺术与现代技术融合的创新方式&#xff01; ✨ 2: Supertone Shift 实时自由…

基于零一万物多模态大模型通过外接数据方案优化图像文字抽取系统

大模型相关目录 大模型&#xff0c;包括部署微调prompt/Agent应用开发、知识库增强、数据库增强、知识图谱增强、自然语言处理、多模态等大模型应用开发内容 从0起步&#xff0c;扬帆起航。 大模型应用向开发路径&#xff1a;AI代理工作流大模型应用开发实用开源项目汇总大模…

深究muduo网络库的Buffer类!!!

最近在学习了muduo库的Buffer类&#xff0c;因为这个编程思想&#xff0c;今后在各个需要缓冲区的项目编程中都可以用到&#xff0c;所以今天来总结一下&#xff01; Buffer的数据结构 muduo的Buffer的定义如下&#xff0c;其内部是 一个 std::vector&#xff0c;且还存在两个…

Pyecharts的编程环境准备

一&#xff0c;准备Python编程环境&#xff1a; Python版本&#xff1a;3.10以上&#xff0c;最高版本3.12 https://www.python.org/ 进入官网&#xff0c;点击downloads—>windows进入下载页面&#xff0c;搜索”3.10.6”找到指定版本&#xff0c;下载并安装64位Installer…

ai智能答题助手,这四款软件让知识触手可及!

在数字化时代&#xff0c;知识的获取变得前所未有的便捷。随着人工智能技术的不断发展&#xff0c;AI智能答题助手应运而生&#xff0c;成为了人们学习、工作和生活中的得力助手。今天&#xff0c;就为大家介绍四款备受欢迎的AI智能答题助手软件&#xff0c;让你感受知识的魅力…

string讲解和实现

认识string string是将basic_string<char>重新定义了 basic_string是一个类模板&#xff0c;里面包括了一些列的有关字符的函数 注意&#xff1a;insert/erase/replace能不要就不用&#xff0c;他们都涉及挪动数据&#xff0c;效率不高 size_t注意 面对无符号整形size_t在…
最新文章