addView()后子布局不居中问题总结与分析

本文详细分析了在Android中,使用addView添加子布局后,子布局未能居中的原因。问题源于不同类型的ViewGroup对LayoutParams的默认处理不同,如FrameLayout默认MATCH_PARENT,而RelativeLayout则是WRAP_CONTENT。解决方案是明确指定LayoutParams,并使用addView(View child, LayoutParams params)方法,确保与父布局类型一致,以避免显示问题。" 105977070,7720750,前端环境搭建与配置:Node.js、NPM、Webpack与VSCode,"['前端开发', 'Node.js', '包资源管理', 'webpack', 'Visual Studio Code']
摘要由CSDN通过智能技术生成

题记

最近项目中遇到一个问题,一个自定义view使用addview加入父布局后,突然不居中了,原因是对父布局增加了一层嵌套;分析类似的问题前我们首先需要理解LayoutParams概念。


LayoutParams

Android SDK中的介绍如下:

LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.

The base LayoutParams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of:

    FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)
    WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding)
    an exact number 

There are subclasses of LayoutParams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of LayoutParams which adds an X and Y value.

其实这个LayoutParams类是用于child view(子视图) 向 parent view(父视图)传达自己的意愿的一个东西(孩子想变成什么样向其父亲说明)其实子视图父视图可以简单理解成。需要注意的是LayoutParams只是ViewGroup的一个内部类,也就是ViewGroup里边这个LayoutParams类是 base class 基类,实际上每个不同的ViewGroup都有自己的LayoutParams子类,比如LinearLayout 也有自己的 LayoutParams;RelativeLayout也有自己的LayoutParams;


问题描述

代码功能为:在activity中动态添加一个TextView,使TextView文本居中;

居中代码如下(没有问题):
xml布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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_wi
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值