题记
最近项目中遇到一个问题,一个自定义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