Android-View详细学习

2017/6/20 posted in  Android

View有8个直接子类:

AnalogClock, ImageView, KeyboardView, ProgressBar, SurfaceView, TextView, ViewGroup, ViewStub

View有54个间接子类:

AbsListView, AbsSeekBar,AbsSpinner, AbsoluteLayout, AdapterView<T extends Adapter>, AppWidgetHostView, AutoCompleteTextView,Button,CheckBox, CheckedTextView, Chronometer, CompoundButton,DatePicker, DialerFilter, DigitalClock,EditText, ExpandableListView, ExtractEditText,FrameLayout, GLSurfaceView,Gallery,GestureOverlayView,GridView, HorizontalScrollView, ImageButton, ImageSwitcher, LinearLayout,ListView,MediaController, MultiAutoCompleteTextView, QuickContactBadge,RadioButton,RadioGroup, RatingBarRelativeLayoutScrollViewSeekBar, SlidingDrawer, Spinner, TabHost, TabWidget, TableLayout, TableRow, TextSwitcher, TimePicker, ToggleButton, TwoLineListItem,VideoView, ViewAnimator, ViewFlipper, ViewSwitcherWebView, ZoomButton, ZoomControls

View的属性

基本属性

  • android:alpha关联方法: setAlpha(float) 属性说明: 视图透明度,值在0-1之间。0为完全透明,1为完全不透明。

  • android:background关联方法: setBackgroundResource(int) 属性说明: 视图背景

  • android:clickable关联方法: setClickable(boolean) 属性说明: 视图是否可点击

  • android:contentDescription关联方法: setContentDescription(CharSequence) 属性说明: 设置View的备注说明,作为一种辅助功能提供,为一些没有文字描述的View提供说明

  • android:drawingCacheQuality关联方法: setDrawingCacheQuality(int) 属性说明: "设置绘图时半透明质量。有可以取以下3个值 auto——默认,由框架决定 high——高质量,使用较高的颜色深度,消耗更多的内存 low——低质量,使用较低的颜色深度,但是用更少的内存"

  • android:duplicateParentState关联方法: 属性说明: 如果设置此属性,将直接从父容器中获取绘图状态(光标,按下等)

  • android:fadeScrollbars关联方法: setScrollbarFadingEnabled(boolean) 属性说明: 定义在ScrollBar没有使用时,是否褪色。

  • android:fadingEdgeLength关联方法: getVerticalFadingEdgeLength() 属性说明: 设置边框渐变的长度。

  • android:filterTouchesWhenObscured关联方法: setFilterTouchesWhenObscured(boolean) 属性说明: view所在窗口被其它可见窗口遮住时,是否过滤触摸事件。

  • android:fitsSystemWindows关联方法: setFitsSystemWindows(boolean) 属性说明: 设置布局调整时是否考虑系统窗口(如状态栏)

  • android:focusable关联方法: setFocusable(boolean) 属性说明: 设置是否获得焦点。若有requestFocus()被调用时,后者优先处理。注意在表单中想设置某一个如EditText获取焦点,光设置这个是不行的,需要将这个EditText前面的focusable都设置为false才行。在Touch模式下获取焦点需要设置focusableInTouchMode为true。

  • android:focusableInTouchMode关联方法: setFocusableInTouchMode(boolean) 属性说明: 设置在Touch模式下View是否能取得焦点。

  • android:hapticFeedbackEnabled关联方法: setHapticFeedbackEnabled(boolean) 属性说明: 是否启用触摸反馈,启用后就是在点击等操作时会有震动等反馈效果

  • android:id关联方法: setId(int) 属性说明: 给当前View设置一个在当前layout.xml中的唯一编号,可以通过调用View.findViewById()Activity.findViewById()根据这个编号查找到对应的View。不同的layout.xml之间定义相同的id不会冲突。

  • android:importantForAccessibility关联方法: setImportantForAccessibility(int) 属性说明: 设置可达性的重要性

  • android:isScrollContainer关联方法: setScrollContainer(boolean) 属性说明: 设置当前View为滚动容器。这里没有测试出效果来,ListView/ GridView/ ScrollView根本就不用设置这个属性,而EdidText设置android:scrollbars也能出滚动条

  • android:keepScreenOn关联方法: setKeepScreenOn(boolean) 属性说明: 视图在可见的情况下是否保持唤醒状态。

  • android:layerType关联方法: setLayerType(int,Paint) 属性说明: "设置指定层的类型,可以取以下3个值: none——不指定 software——软件层。 hardware——硬件层。使用硬件加速。"

  • android:layoutDirection关联方法: setLayoutDirection(int) 属性说明: 定义布局图纸的方向

  • android:longClickable关联方法: setLongClickable(boolean) 属性说明: 是否响应长点击事件

  • android:minHeight关联方法: setMinimumHeight(int) 属性说明: 设置视图最小高度

  • android:minWidth关联方法: setMinimumWidth(int) 属性说明: 设置视图最小宽度

  • android:nextFocusDown关联方法: setNextFocusDownId(int) 属性说明: 向下移动焦点时,下一个获取焦点的view的id

  • android:nextFocusForward关联方法: setNextFocusForwardId(int) 属性说明: 下一个获取焦点的view的id

  • android:nextFocusLeft关联方法: setNextFocusLeftId(int) 属性说明: 向左移动焦点时,下一个获取焦点的view的id

  • android:nextFocusRight关联方法: setNextFocusRightId(int) 属性说明: 向右移动焦点时,下一个获取焦点的view的id

  • android:nextFocusUp关联方法: setNextFocusUpId(int) 属性说明: 向上移动焦点时,下一个获取焦点的view的id

  • android:onClick关联方法: 属性说明: 点击时,要调用的方法的名称。

  • android:padding关联方法: setPaddingRelative(int,int,int,int) 属性说明: 设置上下左右的边距

  • android:paddingBottom关联方法: setPaddingRelative(int,int,int,int) 属性说明: 下边距

  • android:paddingEnd关联方法: setPaddingRelative(int,int,int,int) 属性说明: 与android:paddingRight相同

  • android:paddingLeft关联方法: setPadding(int,int,int,int) 属性说明: 左边距

  • android:paddingRight关联方法: setPadding(int,int,int,int) 属性说明: 右边距

  • android:paddingStart关联方法: setPaddingRelative(int,int,int,int) 属性说明: android:paddingLeft相同

  • android:paddingTop关联方法: setPaddingRelative(int,int,int,int) 属性说明: 上边距

  • android:requiresFadingEdge关联方法: setVerticalFadingEdgeEnabled(boolean) 属性说明: 定义滚动时边缘是否褪色

  • android:rotation关联方法: setRotation(float) 属性说明: 旋转度数

  • android:rotationX关联方法: setRotationX(float) 属性说明: 水平旋转度数

  • android:rotationY关联方法: setRotationY(float) 属性说明: 竖直旋转度数

  • android:saveEnabled关联方法: setSaveEnabled(boolean) 属性说明: 在配置改变等情况出现时是否保存view的状态数据。如果你的view有id,那默认系统就会帮你保存。

  • android:scaleX关联方法: setScaleX(float) 属性说明: 水平方向缩放比例

  • android:scaleY关联方法: setScaleY(float) 属性说明: 竖直方向缩放比例

  • android:scrollX关联方法: 属性说明: x方向的滚动偏移。即在水平方向滚动了多少距离

  • android:scrollY关联方法: 属性说明: y方向的滚动偏移。即在竖直方向滚动了多少距离

  • android:scrollbarAlwaysDrawHorizontalTrack关联方法: 属性说明: 是否总是绘制水平滚动条的滚动轨道

  • android:scrollbarAlwaysDrawVerticalTrack关联方法: 属性说明: 是否总是绘制竖直滚动条的滚动轨道

  • android:scrollbarDefaultDelayBeforeFade关联方法: setScrollBarDefaultDelayBeforeFade(int) 属性说明: 滚动条在n毫秒后开始淡出。

  • android:scrollbarFadeDuration关联方法: setScrollBarFadeDuration(int) 属性说明: 滚动条用多长时间淡出完毕。

  • android:scrollbarSize关联方法: setScrollBarSize(int) 属性说明: 设置滚动条的尺寸。垂直滚动条的宽度、水平滚动条的高度

  • android:scrollbarStyle关联方法: setScrollBarStyle(int) 属性说明: "滚动条的风格。共4组值: insideOverlay——内贴图 insideInset——内插图 outsideOverlay——外贴图 outsideInset——外插图。 inside就是滚动条在绘制在padding以内;outside就是不需要绘制在padding内(即view的边界处);Overlay是贴图,就是直接覆盖在内容的上方,这样内容可能会显示到滚动条下方去;Inset是插图,就是会在对应padding上加上滚动条的宽度,以不让内容显示到滚动条下面去。"

  • android:scrollbarThumbHorizontal关联方法: 属性说明: 水平滚动块的drawable对象

  • android:scrollbarThumbVertical关联方法: 属性说明: 竖直滚动块的drawable对象

  • android:scrollbarTrackHorizontal关联方法: 属性说明: 水平滚动条滚动轨道的drawable对象

  • android:scrollbarTrackVertical关联方法: 属性说明: 竖直滚动条滚动轨道的drawable对象

  • android:scrollbars关联方法: 属性说明: "设置可显示的滚动条。有3个取值: none——不显示滚动条 horizontal——显示水平滚动条 vertical——显示竖直滚动条"

  • android:soundEffectsEnabled关联方法: setSoundEffectsEnabled(boolean) 属性说明: 点击或触摸该view时,是否需要有声音效果

  • android:tag关联方法: 属性说明: string标识。类似id,id是整数标识。

  • android:textAlignment关联方法: setTextAlignment(int) 属性说明: 设置文本的显示方式。

  • android:textDirection关联方法: setTextDirection(int) 属性说明: 设置文本的显示方向。

  • android:transformPivotX关联方法: setPivotX(float) 属性说明: 水平方向偏转量

  • android:transformPivotY关联方法: setPivotY(float) 属性说明: 竖直方向偏转量

  • android:translationX关联方法: setTranslationX(float) 属性说明: 水平方向的移动距离

  • android:translationY关联方法: setTranslationY(float) 属性说明: 竖直方向的移动距离

  • android:visibility关联方法: setVisibility(int) 属性说明: "view的可见性。有3个取值: gone——不可见,同时不占用view的空间; invisible——不可见,但占用view的空间; visible——可见"

TextView属性说明

下面对TextView的属性进行说明android:autoLink关联方法: setAutoLinkMask(int)属性说明: 设置是否“当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接”。可选值(none/web/email/phone/map/all)

  • android:autoText关联方法: setKeyListener(KeyListener)属性说明: 如果设置,将自动执行输入值的拼写纠正。此处无效果,在显示输入法并输入的时候起作用。

  • android:bufferType关联方法: setText(CharSequence,TextView.BufferType)属性说明: 指定getText()方式取得的文本类别。选项editable 类似于StringBuilder可追加字符,也就是说getText后可调用append方法设置文本内容。

  • android:capitalize关联方法: setKeyListener(KeyListener)属性说明: 设置自动大写属性。比如设置为2,自动大写单词首字符;设置为1,自动大写每句话的首字母等等。

  • android:cursorVisible关联方法: setCursorVisible(boolean)属性说明: 设定光标为显示/隐藏,默认显示。

  • android:digits关联方法: setKeyListener(KeyListener)属性说明: 设置允许输入哪些字符。如“1234567890.+-*/%\n()”

  • android:drawableBottom关联方法: setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)属性说明: 在text的下方输出一个drawable。如果指定一个颜色的话会把text的背景设为该颜色,并且同时和background使用时覆盖后者。

  • android:drawableEnd关联方法: setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)属性说明: 在文本结尾处显示drawable对象。它的值可以是其它资源的引用,比如,"@[+][package:]type:name"或者"?[package:][type:]name";也可以是颜色值,如"#rgb", "#argb", "#rrggbb", or "#aarrggbb"。

  • android:drawableLeft关联方法: setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)属性说明: 在text的左边输出一个drawable。

  • android:drawablePadding关联方法: setCompoundDrawablePadding(int)属性说明: 设置text与drawable的间隔,与drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可设置为负数,单独使用没有效果。

  • android:drawableRight关联方法: setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)属性说明: 在text的右边输出一个drawable。

  • android:drawableStart关联方法: setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)属性说明: 在文本开始处显示drawable对象。它的值可以是其它资源的引用,比如,"@[+][package:]type:name"或者"?[package:][type:]name";也可以是颜色值,如"#rgb", "#argb", "#rrggbb", or "#aarrggbb"。

  • android:drawableTop关联方法: setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)属性说明: 在text的正上方输出一个drawable。

  • android:editable关联方法: 属性说明: 设置是否可编辑。这里无效果,在EditView中才有效果。

  • android:editorExtras关联方法: setInputExtras(int)属性说明: 设置文本的额外的输入数据。在EditView中才有效果。

  • android:ellipsize关联方法: setEllipsize(TextUtils.TruncateAt)属性说明: 设置当文字过长时,该控件该如何显示。有如下值设置:”start”—–省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee” ——以跑马灯的方式显示(动画横向移动)

  • android:ems关联方法: setEms(int)属性说明: 设置TextView的宽度为N个字符的宽度。

  • android:fontFamily关联方法: setTypeface(Typeface)属性说明: 文本的字形体系。

  • android:freezesText关联方法: setFreezesText(boolean)属性说明: 设置保存文本的内容以及光标的位置。

  • android:gravity关联方法: setGravity(int)属性说明: 设置文本位置,如设置成“center”,文本将居中显示。

  • android:height关联方法: setHeight(int)属性说明: 设置文本区域的高度,支持度量单位:px(像素)/dp/sp/in/mm(毫米)

  • android:hint关联方法: setHint(int)属性说明: Text为空时显示的文字提示信息,可通过textColorHint设置提示信息的颜色。

  • android:imeActionId关联方法: setImeActionLabel(CharSequence,int)属性说明: 设置IME动作ID。

  • android:imeActionLabel关联方法: setImeActionLabel(CharSequence,int)属性说明: 设置IME动作标签。在EditView再做说明。

  • android:imeOptions关联方法: setImeOptions(int)属性说明: 附加功能,设置右下角IME动作与编辑框相关的动作,如actionDone右下角将显示一个“完成”,而不设置默认是一个回车符号。

  • android:includeFontPadding关联方法: setIncludeFontPadding(boolean)属性说明: 设置文本是否包含顶部和底部额外空白,默认为true。

  • android:inputMethod关联方法: setKeyListener(KeyListener)属性说明: 为文本指定输入法,需要完全限定名(完整的包名)。例如:com.google.android.inputmethod.pinyin,但是这里报错找不到。

  • android:inputType关联方法: setRawInputType(int)属性说明: 设置文本的类型,用于帮助输入法显示合适的键盘类型。在EditView中再详细说明,这里无效果。

  • android:lineSpacingExtra关联方法: setLineSpacing(float,float)属性说明: 设置行间距。

  • android:lineSpacingMultiplier关联方法: setLineSpacing(float,float)属性说明: 设置行间距的倍数。如”1.2”

  • android:lines关联方法: setLines(int)属性说明: 设置文本的行数,设置两行就显示两行,即使第二行没有数据。

  • android:linksClickable关联方法: setLinksClickable(boolean)属性说明: 设置链接是否点击连接,即使设置了autoLink。

  • android:marqueeRepeatLimit关联方法: setMarqueeRepeatLimit(int)属性说明: 在ellipsize指定marquee的情况下,设置重复滚动的次数,当设置为marquee_forever时表示无限次。

  • android:maxEms关联方法: setMaxEms(int)属性说明: 设置TextView的宽度为最长为N个字符的宽度。与ems同时使用时覆盖ems选项。

  • android:maxHeight关联方法: setMaxHeight(int)属性说明: 设置文本区域的最大高度

  • android:maxLength关联方法: setFilters(InputFilter)属性说明: 限制显示的文本长度,超出部分不显示。

  • android:maxLines关联方法: setMaxLines(int)属性说明: 设置文本的最大显示行数,与width或者layout_width结合使用,超出部分自动换行,超出行数将不显示。

  • android:maxWidth关联方法: setMaxWidth(int)属性说明: 设置文本区域的最大宽度

  • android:minEms关联方法: setMinEms(int)属性说明: 设置TextView的宽度为最短为N个字符的宽度。与ems同时使用时覆盖ems选项。

  • android:minHeight关联方法: setMinHeight(int)属性说明: 设置文本区域的最小高度

  • android:minLines关联方法: setMinLines(int)属性说明: 设置文本的最小行数,与lines类似。

  • android:minWidth关联方法: setMinWidth(int)属性说明: 设置文本区域的最小宽度

  • android:numeric关联方法: setKeyListener(KeyListener)属性说明: 如果被设置,该TextView有一个数字输入法。此处无用,设置后唯一效果是TextView有点击效果,此属性在EdtiView将详细说明。

  • android:password关联方法: setTransformationMethod(TransformationMethod)属性说明: 以小点”.”显示文本

  • android:phoneNumber关联方法: setKeyListener(KeyListener)属性说明: 设置为电话号码的输入方式。

  • android:privateImeOptions关联方法: setPrivateImeOptions(String)属性说明: 设置输入法选项,在EditText中才有作用。

  • android:scrollHorizontally关联方法: setHorizontallyScrolling(boolean)属性说明: 设置文本超出TextView的宽度的情况下,是否出现横拉条。

  • android:selectAllOnFocus关联方法: setSelectAllOnFocus(boolean)属性说明: 如果文本是可选择的,让他获取焦点而不是将光标移动为文本的开始位置或者末尾位置。TextView中设置后无效果。

  • android:shadowColor关联方法: setShadowLayer(float,float,float,int)属性说明: 指定文本阴影的颜色,需要与shadowRadius一起使用。

  • android:shadowDx关联方法: setShadowLayer(float,float,float,int)属性说明: 设置阴影横向坐标开始位置。

  • android:shadowDy关联方法: setShadowLayer(float,float,float,int)属性说明: 设置阴影纵向坐标开始位置。

  • android:shadowRadius关联方法: setShadowLayer(float,float,float,int)属性说明: 设置阴影的半径。设置为0.1就变成字体的颜色了,一般设置为3.0的效果比较好。

  • android:singleLine关联方法: setTransformationMethod(TransformationMethod)属性说明: 设置单行显示。如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。如android:text="test_ singleLine" android:singleLine="true" android:layout_width="20dp"将只显示“t…”。如果不设置singleLine或者设置为false,文本将自动换行

  • android:text关联方法: setText(CharSequence,TextView.BufferType)属性说明: 设置显示文本.

  • android:textAllCaps关联方法: setAllCaps(boolean)属性说明: 设置文本全为大写。值为"true"或"false"。

  • android:textAppearance关联方法: 属性说明: 设置文字外观。如“?android:attr/textAppearanceLargeInverse

  • android:textColor关联方法: setTextColor(int)属性说明: 设置文本颜色

  • android:textColorHighlight关联方法: setHighlightColor(int)属性说明: 被选中文字的底色,默认为蓝色

  • android:textColorHint关联方法: setHintTextColor(int)属性说明: 设置提示信息文字的颜色,默认为灰色。与hint一起使用。

  • android:textColorLink关联方法: setLinkTextColor(int)属性说明: 文字链接的颜色.

  • android:textIsSelectable关联方法: isTextSelectable()属性说明: 设置非编辑文本可否被选择。值为"true"或"false"。

  • android:textScaleX关联方法: setTextScaleX(float)属性说明: 设置文字之间间隔,默认为1.0f。

  • android:textSize关联方法: setTextSize(int,float)属性说明: 设置文字大小,推荐度量单位”sp”,如”15sp”

  • android:textStyle关联方法: setTypeface(Typeface)属性说明: 设置字形[bold(粗体) 0, italic(斜体) 1, bolditalic(又粗又斜) 2] 可以设置一个或多个,用“|”隔开

  • android:typeface关联方法: setTypeface(Typeface)属性说明: 设置文本字体,必须是以下常量值之一:normal 0, sans 1, serif 2, monospace(等宽字体) 3]

  • android:width关联方法: setWidth(int)属性说明: 设置文本区域的宽度,支持度量单位:px(像素)/dp/sp/in/mm(毫米)。

Other

由于这两天在做listView的东西,所以整理出来一些我个人认为比较特别的属性,通过设置这样的属性可以做出更加美观的列表

  • 首先是stackFromBottom属性,这只该属性之后你做好的列表就会显示你列表的最下面,值为true和false

android:stackFromBottom="true"

  • 第二是transciptMode属性,需要用ListView或者其它显示大量Items的控件实时跟踪或者查看信息,并且希望最新的条目可以自动滚动到可视范围内。通过设置的控件transcriptMode属性可以将 android平台的控件(支持ScrollBar)自动滑动到最底部。 android:transcriptMode="alwaysScroll"

  • 第三cacheColorHint属性,很多人希望能够改变一下它的背景,使他能够符合整体的UI设计,改变背景背很简单只需要准备一张图片然后指定属性 android:background="@drawable/bg",不过不要高兴地太早,当你这么做以后,发现背景是变了,但是当你拖动,或者点击list空白位置的时候发现ListItem都变成黑色的了,破坏了整体效果。

如果你只是换背景的颜色的话,可以直接指定android:cacheColorHint为你所要的颜色,如果你是用图片做背景的话,那也只要将android:cacheColorHint指定为透明(#00000000)就可以了

  • 第四divider属性,该属性作用是每一项之间需要设置一个图片做为间隔,或是去掉item之间的分割线

android:divider="@drawable/list_driver"  其中  @drawable/list_driver 是一个图片资源,如果不想显示分割线则只要设置为android:divider="@drawable/@null" 就可以了

  • 第五fadingEdge属性,上边和下边有黑色的阴影

android:fadingEdge="none" 设置后没有阴影了~

  • 第六scrollbars属性,作用是隐藏listView的滚动条,

android:scrollbars="none"setVerticalScrollBarEnabled(true);的效果是一样的,不活动的时候隐藏,活动的时候也隐藏

  • 第七fadeScrollbars属性,android:fadeScrollbars="true"  配置ListView布局的时候,设置这个属性为true就可以实现滚动条的自动隐藏和显示。

自定义View的方法

常用方法

  • onFinishInflate() 当View中所有的子控件均被映射成xml后触发
  • onMeasure(int, int) 确定所有子元素的大小
  • onLayout(boolean, int, int, int, int) 当View分配所有的子元素的大小和位置时触发
  • onSizeChanged(int, int, int, int) 当view的大小发生变化时触发
  • onDraw(Canvas) view渲染内容的细节
  • onKeyDown(int, KeyEvent) 有按键按下后触发
  • onKeyUp(int, KeyEvent) 有按键按下后弹起时触发
  • onTrackballEvent(MotionEvent) 轨迹球事件
  • onTouchEvent(MotionEvent) 触屏事件
  • onFocusChanged(boolean, int, Rect) 当View获取或失去焦点时触发
  • onWindowFocusChanged(boolean) 当窗口包含的view获取或失去焦点时触发
  • onAttachedToWindow() 当view被附着到一个窗口时触发
  • onDetachedFromWindow() 当view离开附着的窗口时触发,提示该方法和 onAttachedToWindow() 是相反的。
  • onWindowVisibilityChanged(int) 当窗口中包含的可见的view发生变化时触发

公用方法

  • void addChildrenForAccessibility(ArrayList<View> outChildren) Adds the children of this View relevant for accessibility to the given list as output.
  • void addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo info, String extraDataKey, Bundle arguments) Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.
  • void addFocusables(ArrayList<View> views, int direction) Add any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views.
  • void addFocusables(ArrayList<View> views, int direction, int focusableMode) Adds any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views.
  • void addKeyboardNavigationClusters(Collection<View> views, int direction) Adds any keyboard navigation cluster roots that are descendants of this view (possibly including this view if it is a cluster root itself) to views.
  • void addOnAttachStateChangeListener(View.OnAttachStateChangeListener listener) Add a listener for attach state changes.
  • void addOnLayoutChangeListener(View.OnLayoutChangeListener listener) Add a listener that will be called when the bounds of the view change due to layout processing.
  • void addTouchables(ArrayList<View> views) Add any touchable views that are descendants of this view (possibly including this view if it is touchable itself) to views.
  • ViewPropertyAnimator animate() This method returns a ViewPropertyAnimator object, which can be used to animate specific properties on this View.
  • void announceForAccessibility(CharSequence text) Convenience method for sending a TYPE_ANNOUNCEMENT AccessibilityEvent to make an announcement which is related to some sort of a context change for which none of the events representing UI transitions is a good fit.
  • void autoFill(AutoFillValue value) Automatically fills the content of this view with the value.
  • void autoFillVirtual(int virtualId, AutoFillValue value) Automatically fills the content of a virtual view with the value
    See autoFill(AutoFillValue) and onProvideAutoFillVirtualStructure(ViewStructure, int) for more info.
  • void bringToFront() Change the view's z order in the tree, so it's on top of other sibling views.
  • void buildDrawingCache(boolean autoScale) Forces the drawing cache to be built if the drawing cache is invalid.
  • void buildDrawingCache() Calling this method is equivalent to calling buildDrawingCache(false).
  • void buildLayer() Forces this view's layer to be created and this view to be rendered into its layer.
  • boolean callOnClick() Directly call any attached OnClickListener.
  • boolean canResolveLayoutDirection() Check if layout direction resolution can be done.
  • boolean canResolveTextAlignment() Check if text alignment resolution can be done.
  • boolean canResolveTextDirection() Check if text direction resolution can be done.
  • boolean canScrollHorizontally(int direction) Check if this view can be scrolled horizontally in a certain direction.
  • boolean canScrollVertically(int direction) Check if this view can be scrolled vertically in a certain direction.
  • final void cancelDragAndDrop() Cancels an ongoing drag and drop operation.
  • void cancelLongPress() Cancels a pending long press.
  • final void cancelPendingInputEvents() Cancel any deferred high-level input events that were previously posted to the event queue.
  • boolean checkInputConnectionProxy(View view) Called by the InputMethodManager when a view who is not the current input connection target is trying to make a call on the manager.
  • void clearAnimation() Cancels any animations for this view.
  • void clearFocus() Called when this view wants to give up focus.
    static int combineMeasuredStates(int curState, int newState)
    Merge two states as returned by getMeasuredState().
  • void computeScroll() Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.
  • WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) Compute insets that should be consumed by this view and the ones that should propagate to those under it.
  • AccessibilityNodeInfo createAccessibilityNodeInfo() Returns an AccessibilityNodeInfo representing this view from the point of view of an AccessibilityService.
  • void createContextMenu(ContextMenu menu) Show the context menu for this view.
  • void destroyDrawingCache() Frees the resources used by the drawing cache.
  • WindowInsets dispatchApplyWindowInsets(WindowInsets insets) Request to apply the given window insets to this view or another view in its subtree.
  • boolean dispatchCapturedPointerEvent(MotionEvent event) Pass a captured pointer event down to the focused view.
  • void dispatchConfigurationChanged(Configuration newConfig) Dispatch a notification about a resource configuration change down the view hierarchy.
  • void dispatchDisplayHint(int hint) Dispatch a hint about whether this view is displayed.
  • boolean dispatchDragEvent(DragEvent event) Detects if this View is enabled and has a drag event listener.
  • void dispatchDrawableHotspotChanged(float x, float y) Dispatches drawableHotspotChanged to all of this View's children.
  • void dispatchFinishTemporaryDetach() Dispatch onFinishTemporaryDetach() to this View and its direct children if this is a container View.
  • boolean dispatchGenericMotionEvent(MotionEvent event) Dispatch a generic motion event.
  • boolean dispatchKeyEvent(KeyEvent event) Dispatch a key event to the next view on the focus path.
  • boolean dispatchKeyEventPreIme(KeyEvent event) Dispatch a key event before it is processed by any input method associated with the view hierarchy.
  • boolean dispatchKeyShortcutEvent(KeyEvent event) Dispatches a key shortcut event.
  • boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) Dispatch a fling to a nested scrolling parent.
  • boolean dispatchNestedPreFling(float velocityX, float velocityY) Dispatch a fling to a nested scrolling parent before it is processed by this view.
  • boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) Report an accessibility action to this view's parents for delegated processing.
  • boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
  • boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) Dispatch one step of a nested scroll in progress.
  • void dispatchPointerCaptureChanged(boolean hasCapture)
  • boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event.
  • void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) Dispatch creation of ViewStructure down the hierarchy.
  • void dispatchProvideStructure(ViewStructure structure) Dispatch creation of ViewStructure down the hierarchy.
  • void dispatchStartTemporaryDetach() Dispatch onStartTemporaryDetach() to this View and its direct children if this is a container View.
  • void dispatchSystemUiVisibilityChanged(int visibility) Dispatch callbacks to setOnSystemUiVisibilityChangeListener(View.OnSystemUiVisibilityChangeListener) down the view hierarchy.
  • boolean dispatchTouchEvent(MotionEvent event) Pass the touch screen motion event down to the target view, or this view if it is the target.
  • boolean dispatchTrackballEvent(MotionEvent event) Pass a trackball motion event down to the focused view.
    boolean dispatchUnhandledMove(View focused, int direction)
    This method is the last chance for the focused view and its ancestors to respond to an arrow key.
  • void dispatchWindowFocusChanged(boolean hasFocus) Called when the window containing this view gains or loses window focus.
  • void dispatchWindowSystemUiVisiblityChanged(int visible) Dispatch callbacks to onWindowSystemUiVisibilityChanged(int) down the view hierarchy.
  • void dispatchWindowVisibilityChanged(int visibility) Dispatch a window visibility change down the view hierarchy.
  • void draw(Canvas canvas) Manually render this view (and all of its children) to the given Canvas.
  • void drawableHotspotChanged(float x, float y) This function is called whenever the view hotspot changes and needs to be propagated to drawables or child views managed by the view.
  • View findFocus() Find the view in the hierarchy rooted at this view that currently has focus.
  • final <T extends View> T findViewById(int id) Look for a child view with the given id.
  • final <T extends View> T findViewWithTag(Object tag) Look for a child view with the given tag.
  • void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) Finds the Views that contain given text.
  • View focusSearch(int direction) Find the nearest view in the specified direction that can take focus.
  • void forceHasOverlappingRendering(boolean hasOverlappingRendering) Sets the behavior for overlapping rendering for this view (see hasOverlappingRendering() for more details on this behavior).
  • void forceLayout() Forces this view to be laid out during the next layout pass.
  • static int generateViewId() Generate a value suitable for use in setId(int).
  • CharSequence getAccessibilityClassName() Return the class name of this object to be used for accessibility purposes.
  • int getAccessibilityLiveRegion() Gets the live region mode for this View.
  • AccessibilityNodeProvider getAccessibilityNodeProvider() Gets the provider for managing a virtual view hierarchy rooted at this View and reported to AccessibilityServices that explore the window content.
  • int getAccessibilityTraversalAfter() Gets the id of a view after which this one is visited in accessibility traversal.
  • int getAccessibilityTraversalBefore() Gets the id of a view before which this one is visited in accessibility traversal.
  • float getAlpha() The opacity of the view.
  • Animation getAnimation() Get the animation currently associated with this view.
  • IBinder getApplicationWindowToken() Retrieve a unique token identifying the top-level "real" window of the window that this view is attached to.
  • int getAutoFillMode() Returns the auto-fill mode for this view.
  • AutoFillType getAutoFillType() Describes the auto-fill type that should be used on calls to autoFill(AutoFillValue) and autoFillVirtual(int, AutoFillValue).
  • AutoFillValue getAutoFillValue() Gets the View's current auto-fill value.
  • Drawable getBackground() Gets the background drawable
  • ColorStateList getBackgroundTintList() Return the tint applied to the background drawable, if specified.
  • PorterDuff.Mode getBackgroundTintMode() Return the blending mode used to apply the tint to the background drawable, if specified.
  • int getBaseline() Return the offset of the widget's text baseline from the widget's top boundary.
  • final int getBottom() Bottom position of this view relative to its parent.
  • float getCameraDistance() Gets the distance along the Z axis from the camera to this view.
  • boolean getClipBounds(Rect outRect) Populates an output rectangle with the clip bounds of the view, returning true if successful or false if the view's clip bounds are null.
  • Rect getClipBounds() Returns a copy of the current clipBounds.
  • final boolean getClipToOutline() Returns whether the Outline should be used to clip the contents of the View.
  • CharSequence getContentDescription() Returns the View's content description.
  • final Context getContext() Returns the context the view is running in, through which it can access the current theme, resources, etc.
  • static int getDefaultSize(int size, int measureSpec) Utility to return a default size.
  • Display getDisplay() Gets the logical display to which the view's window has been attached.
  • final int[] getDrawableState() Return an array of resource IDs of the drawable states representing the current state of the view.
  • Bitmap getDrawingCache() Calling this method is equivalent to calling getDrawingCache(false).
  • Bitmap getDrawingCache(boolean autoScale) Returns the bitmap in which this view drawing is cached.
  • int getDrawingCacheBackgroundColor()
  • int getDrawingCacheQuality() Returns the quality of the drawing cache.
  • void getDrawingRect(Rect outRect) Return the visible drawing bounds of your view.
  • long getDrawingTime() Return the time at which the drawing of the view hierarchy started.
  • float getElevation() The base elevation of this view relative to its parent, in pixels.
  • boolean getFilterTouchesWhenObscured() Gets whether the framework should discard touches when the view's window is obscured by another visible window.
  • boolean getFitsSystemWindows() Check for state of setFitsSystemWindows(boolean).
  • int getFocusable() Returns the focusable setting for this view.
  • ArrayList<View> getFocusables(int direction) Find and return all focusable views that are descendants of this view, possibly including this view if it is focusable itself.
  • void getFocusedRect(Rect r) When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method.
  • Drawable getForeground() Returns the drawable used as the foreground of this View.
  • int getForegroundGravity() Describes how the foreground is positioned.
  • ColorStateList getForegroundTintList() Return the tint applied to the foreground drawable, if specified.
  • PorterDuff.Mode getForegroundTintMode() Return the blending mode used to apply the tint to the foreground drawable, if specified.
  • final boolean getGlobalVisibleRect(Rect r)
  • boolean getGlobalVisibleRect(Rect r, Point globalOffset) If some part of this view is not clipped by any of its parents, then return that area in r in global (root) coordinates.
  • Handler getHandler()
  • final boolean getHasOverlappingRendering() Returns the value for overlapping rendering that is used internally.
  • final int getHeight() Return the height of your view.
  • void getHitRect(Rect outRect) Hit rectangle in parent's coordinates
  • int getHorizontalFadingEdgeLength() Returns the size of the horizontal faded edges used to indicate that more content in this view is visible.
  • int getId() Returns this view's identifier.
    int getImportantForAccessibility()
    Gets the mode for determining whether this View is important for accessibility.
  • boolean getKeepScreenOn() Returns whether the screen should remain on, corresponding to the current value of KEEP_SCREEN_ON.
  • KeyEvent.DispatcherState getKeyDispatcherState() Return the global KeyEvent.DispatcherState for this view's window.
  • int getLabelFor() Gets the id of a view for which this view serves as a label for accessibility purposes.
  • int getLayerType() Indicates what type of layer is currently associated with this view.
  • int getLayoutDirection() Returns the resolved layout direction for this view.
  • ViewGroup.LayoutParams getLayoutParams() Get the LayoutParams associated with this view.
  • final int getLeft() Left position of this view relative to its parent.
  • final boolean getLocalVisibleRect(Rect r)
  • void getLocationInWindow(int[] outLocation) Computes the coordinates of this view in its window.
  • void getLocationOnScreen(int[] outLocation) Computes the coordinates of this view on the screen.
  • Matrix getMatrix() The transform matrix of this view, which is calculated based on the current rotation, scale, and pivot properties.
  • final int getMeasuredHeight() Like getMeasuredHeightAndState(), but only returns the raw height component (that is the result is masked by MEASURED_SIZE_MASK).
  • final int getMeasuredHeightAndState() Return the full height measurement information for this view as computed by the most recent call to measure(int, int).
  • final int getMeasuredState() Return only the state bits of getMeasuredWidthAndState() and getMeasuredHeightAndState(), combined into one integer.
  • final int getMeasuredWidth() Like getMeasuredWidthAndState(), but only returns the raw width component (that is the result is masked by MEASURED_SIZE_MASK).
  • final int getMeasuredWidthAndState() Return the full width measurement information for this view as computed by the most recent call to measure(int, int).
  • int getMinimumHeight() Returns the minimum height of the view.
  • int getMinimumWidth() Returns the minimum width of the view.
  • int getNextClusterForwardId() Gets the id of the root of the next keyboard navigation cluster.
  • int getNextFocusDownId() Gets the id of the view to use when the next focus is FOCUS_DOWN.
  • int getNextFocusForwardId() Gets the id of the view to use when the next focus is FOCUS_FORWARD.
  • int getNextFocusLeftId() Gets the id of the view to use when the next focus is FOCUS_LEFT.
  • int getNextFocusRightId() Gets the id of the view to use when the next focus is FOCUS_RIGHT.
  • int getNextFocusUpId() Gets the id of the view to use when the next focus is FOCUS_UP.
    View.OnFocusChangeListener getOnFocusChangeListener()
    Returns the focus-change callback registered for this view.
  • ViewOutlineProvider getOutlineProvider() Returns the current ViewOutlineProvider of the view, which generates the Outline that defines the shape of the shadow it casts, and enables outline clipping.
  • int getOverScrollMode() Returns the over-scroll mode for this view.
  • ViewOverlay getOverlay() Returns the overlay for this view, creating it if it does not yet exist.
  • int getPaddingBottom() Returns the bottom padding of this view.
  • int getPaddingEnd() Returns the end padding of this view depending on its resolved layout direction.
  • int getPaddingLeft() Returns the left padding of this view.
  • int getPaddingRight() Returns the right padding of this view.
  • int getPaddingStart() Returns the start padding of this view depending on its resolved layout direction.
  • int getPaddingTop() Returns the top padding of this view.
  • final ViewParent getParent() Gets the parent of this view.
  • ViewParent getParentForAccessibility() Gets the parent for accessibility purposes.
  • float getPivotX() The x location of the point around which the view is rotated and scaled.
  • float getPivotY() The y location of the point around which the view is rotated and scaled.
  • PointerIcon getPointerIcon() Gets the pointer icon for the current view.
  • Resources getResources() Returns the resources associated with this view.
  • final boolean getRevealOnFocusHint() Returns this view's preference for reveal behavior when it gains focus.
  • final int getRight() Right position of this view relative to its parent.
  • View getRootView() Finds the topmost view in the current view hierarchy.
  • WindowInsets getRootWindowInsets() Provide original WindowInsets that are dispatched to the view hierarchy.
  • float getRotation() The degrees that the view is rotated around the pivot point.
  • float getRotationX() The degrees that the view is rotated around the horizontal axis through the pivot point.
  • float getRotationY() The degrees that the view is rotated around the vertical axis through the pivot point.
  • float getScaleX() The amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width.
  • float getScaleY() The amount that the view is scaled in y around the pivot point, as a proportion of the view's unscaled height.
  • int getScrollBarDefaultDelayBeforeFade() Returns the delay before scrollbars fade.
  • int getScrollBarFadeDuration() Returns the scrollbar fade duration.
  • int getScrollBarSize() Returns the scrollbar size.
  • int getScrollBarStyle() Returns the current scrollbar style.
  • int getScrollIndicators() Returns a bitmask representing the enabled scroll indicators.
  • final int getScrollX() Return the scrolled left position of this view.
  • final int getScrollY() Return the scrolled top position of this view.
  • int getSolidColor() Override this if your view is known to always be drawn on top of a solid color background, and needs to draw fading edges.
    StateListAnimator getStateListAnimator()
    Returns the current StateListAnimator if exists.
  • int getSystemUiVisibility() Returns the last setSystemUiVisibility(int) that this view has requested.
  • Object getTag() Returns this view's tag.
  • Object getTag(int key) Returns the tag associated with this view and the specified key.
  • int getTextAlignment() Return the resolved text alignment.
  • int getTextDirection() Return the resolved text direction.
  • CharSequence getTooltipText() Returns the view's tooltip text.
  • final int getTop() Top position of this view relative to its parent.
  • TouchDelegate getTouchDelegate() Gets the TouchDelegate for this View.
  • ArrayList<View> getTouchables() Find and return all touchable views that are descendants of this view, possibly including this view if it is touchable itself.
  • String getTransitionName() Returns the name of the View to be used to identify Views in Transitions.
  • float getTranslationX() The horizontal location of this view relative to its left position.
  • float getTranslationY() The vertical location of this view relative to its top position.
  • float getTranslationZ() The depth location of this view relative to its elevation.
  • int getVerticalFadingEdgeLength() Returns the size of the vertical faded edges used to indicate that more content in this view is visible.
  • int getVerticalScrollbarPosition()
  • int getVerticalScrollbarWidth() Returns the width of the vertical scrollbar.
  • ViewTreeObserver getViewTreeObserver() Returns the ViewTreeObserver for this view's hierarchy.
  • int getVisibility() Returns the visibility status for this view.
  • final int getWidth() Return the width of the your view.
  • WindowId getWindowId() Retrieve the WindowId for the window this view is currently attached to.
  • int getWindowSystemUiVisibility() Returns the current system UI visibility that is currently set for the entire window.
  • IBinder getWindowToken() Retrieve a unique token identifying the window this view is attached to.
  • int getWindowVisibility() Returns the current visibility of the window this view is attached to (either GONE, INVISIBLE, or VISIBLE).
  • void getWindowVisibleDisplayFrame(Rect outRect) Retrieve the overall visible display size in which the window this view is attached to has been positioned in.
  • float getX() The visual x position of this view, in pixels.
  • float getY() The visual y position of this view, in pixels.
  • float getZ() The visual z position of this view, in pixels.
  • boolean hasExplicitFocusable() Returns true if this view is focusable or if it contains a reachable View for which hasExplicitFocusable() returns true.
  • boolean hasFocus() Returns true if this view has focus itself, or is the ancestor of the view that has focus.
  • boolean hasFocusable() Returns true if this view is focusable or if it contains a reachable View for which hasFocusable() returns true.
  • boolean hasNestedScrollingParent() Returns true if this view has a nested scrolling parent.
  • boolean hasOnClickListeners() Return whether this view has an attached OnClickListener.
  • boolean hasOverlappingRendering() Returns whether this View has content which overlaps.
  • boolean hasPointerCapture() Checks pointer capture status.
  • boolean hasTransientState() Indicates whether the view is currently tracking transient state that the app should not need to concern itself with saving and restoring, but that the framework should take special note to preserve when possible.
  • boolean hasWindowFocus() Returns true if this view is in a window that currently has window focus.
  • static View inflate(Context context, int resource, ViewGroup root) Inflate a view from an XML resource.
  • void invalidate() Invalidate the whole view.
  • void invalidate(Rect dirty) Mark the area defined by dirty as needing to be drawn.
  • void invalidate(int l, int t, int r, int b) Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
  • void invalidateDrawable(Drawable drawable) Invalidates the specified Drawable.
  • void invalidateOutline() Called to rebuild this View's Outline from its outline provider
  • boolean isAccessibilityFocused() Returns whether this View is accessibility focused.
  • boolean isActivated() Indicates the activation state of this view.
  • boolean isAttachedToWindow() Returns true if this view is currently attached to a window.
  • boolean isClickable() Indicates whether this view reacts to click events or not.
  • boolean isContextClickable() Indicates whether this view reacts to context clicks or not.
  • boolean isDirty() True if this view has changed since the last time being drawn.
  • boolean isDrawingCacheEnabled() Indicates whether the drawing cache is enabled for this view.
  • boolean isDuplicateParentStateEnabled() Indicates whether this duplicates its drawable state from its parent.
  • boolean isEnabled() Returns the enabled status for this view.
  • final boolean isFocusable() Returns whether this View is currently able to take focus.
  • final boolean isFocusableInTouchMode() When a view is focusable, it may not want to take focus when in touch mode.
  • boolean isFocused() Returns true if this view has focus
  • final boolean isFocusedByDefault() Returns whether this View should receive focus when the focus is restored for the view hierarchy containing this view.
  • boolean isHapticFeedbackEnabled()
  • boolean isHardwareAccelerated() Indicates whether this view is attached to a hardware accelerated window or not.
  • boolean isHorizontalFadingEdgeEnabled() Indicate whether the horizontal edges are faded when the view is scrolled horizontally.
  • boolean isHorizontalScrollBarEnabled() Indicate whether the horizontal scrollbar should be drawn or not.
  • boolean isHovered() Returns true if the view is currently hovered.
  • boolean isImportantForAccessibility() Computes whether this view should be exposed for accessibility.
  • boolean isInEditMode() Indicates whether this View is currently in edit mode.
  • boolean isInLayout() Returns whether the view hierarchy is currently undergoing a layout pass.
  • boolean isInTouchMode() Returns whether the device is currently in touch mode.
  • final boolean isKeyboardNavigationCluster() Returns whether this View is a root of a keyboard navigation cluster.
  • boolean isLaidOut() Returns true if this view has been through at least one layout since it was last attached to or detached from a window.
  • boolean isLayoutDirectionResolved()
  • boolean isLayoutRequested() Indicates whether or not this view's layout will be requested during the next hierarchy layout pass.
  • boolean isLongClickable() Indicates whether this view reacts to long click events or not.
  • boolean isNestedScrollingEnabled() Returns true if nested scrolling is enabled for this view.
  • boolean isOpaque() Indicates whether this View is opaque.
  • boolean isPaddingRelative() Return if the padding has been set through relative values setPaddingRelative(int, int, int, int) or through
  • boolean isPressed() Indicates whether the view is currently in pressed state.
  • boolean isSaveEnabled() Indicates whether this view will save its state (that is, whether its onSaveInstanceState() method will be called).
  • boolean isSaveFromParentEnabled() Indicates whether the entire hierarchy under this view will save its state when a state saving traversal occurs from its parent.
  • boolean isScrollContainer() Indicates whether this view is one of the set of scrollable containers in its window.
  • boolean isScrollbarFadingEnabled() Returns true if scrollbars will fade when this view is not scrolling
  • boolean isSelected() Indicates the selection state of this view.
  • boolean isShown() Returns the visibility of this view and all of its ancestors
  • boolean isSoundEffectsEnabled()
  • final boolean isTemporarilyDetached() Tells whether the View is in the state between onStartTemporaryDetach() and onFinishTemporaryDetach().
  • boolean isTextAlignmentResolved()
  • boolean isTextDirectionResolved()
  • boolean isVerticalFadingEdgeEnabled() Indicate whether the vertical edges are faded when the view is scrolled horizontally.
  • boolean isVerticalScrollBarEnabled() Indicate whether the vertical scrollbar should be drawn or not.
  • void jumpDrawablesToCurrentState() Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.
  • View keyboardNavigationClusterSearch(View currentCluster, int direction) Find the nearest keyboard navigation cluster in the specified direction.
  • void layout(int l, int t, int r, int b) Assign a size and position to a view and all of its descendants
    This is the second phase of the layout mechanism.
  • final void measure(int widthMeasureSpec, int heightMeasureSpec) This is called to find out how big a view should be.
  • void offsetLeftAndRight(int offset) Offset this view's horizontal location by the specified amount of pixels.
  • void offsetTopAndBottom(int offset) Offset this view's vertical location by the specified number of pixels.
  • WindowInsets onApplyWindowInsets(WindowInsets insets) Called when the view should apply WindowInsets according to its internal policy.
  • void onCancelPendingInputEvents() Called as the result of a call to cancelPendingInputEvents() on this view or a parent view.
  • boolean onCapturedPointerEvent(MotionEvent event) Implement this method to handle captured pointer events
  • boolean onCheckIsTextEditor() Check whether the called view is a text editor, in which case it would make sense to automatically display a soft input window for it.
  • InputConnection onCreateInputConnection(EditorInfo outAttrs) Create a new InputConnection for an InputMethod to interact with the view.
  • boolean onDragEvent(DragEvent event) Handles drag events sent by the system following a call to startDragAndDrop().
  • void onDrawForeground(Canvas canvas) Draw any foreground content for this view.
  • boolean onFilterTouchEventForSecurity(MotionEvent event) Filter the touch event to apply security policies.
  • void onFinishTemporaryDetach() Called after onStartTemporaryDetach() when the container is done changing the view.
  • boolean onGenericMotionEvent(MotionEvent event) Implement this method to handle generic motion events.
  • void onHoverChanged(boolean hovered) Implement this method to handle hover state changes.
  • boolean onHoverEvent(MotionEvent event) Implement this method to handle hover events.
  • void onInitializeAccessibilityEvent(AccessibilityEvent event) Initializes an AccessibilityEvent with information about this View which is the event source.
  • void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) Initializes an AccessibilityNodeInfo with information about this view.
  • boolean onKeyDown(int keyCode, KeyEvent event) Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.
  • boolean onKeyLongPress(int keyCode, KeyEvent event) Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).
  • boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
  • boolean onKeyPreIme(int keyCode, KeyEvent event) Handle a key event before it is processed by any input method associated with the view hierarchy.
  • boolean onKeyShortcut(int keyCode, KeyEvent event) Called on the focused view when a key shortcut event is not handled.
  • boolean onKeyUp(int keyCode, KeyEvent event) Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER, KEYCODE_ENTER or KEYCODE_SPACE is released.
  • void onMovedToDisplay(int displayId) Called by the system when the hosting activity is moved from one display to another without recreation.
  • void onPointerCaptureChange(boolean hasCapture) Called when the window has just acquired or lost pointer capture.
  • void onPopulateAccessibilityEvent(AccessibilityEvent event) Called from dispatchPopulateAccessibilityEvent(AccessibilityEvent) giving a chance to this View to populate the accessibility event with its text content.
  • void onProvideAutoFillStructure(ViewStructure structure, int flags) Called when assist structure is being retrieved from a view as part of an auto-fill request.
  • void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) Called when assist structure is being retrieved from a view as part of an auto-fill request to generate additional virtual structure under this view.
  • void onProvideStructure(ViewStructure structure) Called when assist structure is being retrieved from a view as part of Activity.onProvideAssistData.
  • void onProvideVirtualStructure(ViewStructure structure) Called when assist structure is being retrieved from a view as part of Activity.onProvideAssistData to generate additional virtual structure under this view.
  • PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
  • void onRtlPropertiesChanged(int layoutDirection) Called when any RTL property (layout direction or text direction or text alignment) has been changed.
  • void onScreenStateChanged(int screenState) This method is called whenever the state of the screen this view is attached to changes.
  • void onStartTemporaryDetach() This is called when a container is going to temporarily detach a child, with ViewGroup.detachViewFromParent.
  • boolean onTouchEvent(MotionEvent event) Implement this method to handle touch screen motion events.
  • boolean onTrackballEvent(MotionEvent event) Implement this method to handle trackball motion events.
  • void onVisibilityAggregated(boolean isVisible) Called when the user-visibility of this View is potentially affected by a change to this view itself, an ancestor view or the window this view is attached to.
  • void onWindowFocusChanged(boolean hasWindowFocus) Called when the window containing this view gains or loses focus.
  • void onWindowSystemUiVisibilityChanged(int visible) Override to find out when the window's requested system UI visibility has changed, that is the value returned by getWindowSystemUiVisibility().
  • boolean performAccessibilityAction(int action, Bundle arguments) Performs the specified accessibility action on the view.
  • boolean performClick() Call this view's OnClickListener, if it is defined.
  • boolean performContextClick(float x, float y) Call this view's OnContextClickListener, if it is defined.
  • boolean performContextClick() Call this view's OnContextClickListener, if it is defined.
  • boolean performHapticFeedback(int feedbackConstant) Provide haptic feedback to the user for this view.
  • boolean performHapticFeedback(int feedbackConstant, int flags) Like performHapticFeedback(int), with additional options.
  • boolean performLongClick(float x, float y) Calls this view's OnLongClickListener, if it is defined.
  • boolean performLongClick() Calls this view's OnLongClickListener, if it is defined.
  • void playSoundEffect(int soundConstant) Play a sound effect for this view.
  • boolean post(Runnable action) Causes the Runnable to be added to the message queue.
  • boolean postDelayed(Runnable action, long delayMillis) Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses.
  • void postInvalidate() Cause an invalidate to happen on a subsequent cycle through the event loop.
  • void postInvalidate(int left, int top, int right, int bottom) Cause an invalidate of the specified area to happen on a subsequent cycle through the event loop.
  • void postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom) Cause an invalidate of the specified area to happen on a subsequent cycle through the event loop.
  • void postInvalidateDelayed(long delayMilliseconds) Cause an invalidate to happen on a subsequent cycle through the event loop.
  • void postInvalidateOnAnimation(int left, int top, int right, int bottom) Cause an invalidate of the specified area to happen on the next animation time step, typically the next display frame.
  • void postInvalidateOnAnimation() Cause an invalidate to happen on the next animation time step, typically the next display frame.
  • void postOnAnimation(Runnable action) Causes the Runnable to execute on the next animation time step.
    void postOnAnimationDelayed(Runnable action, long delayMillis)
    Causes the Runnable to execute on the next animation time step, after the specified amount of time elapses.
  • void refreshDrawableState() Call this to force a view to update its drawable state.
  • void releasePointerCapture() Releases the pointer capture.
  • boolean removeCallbacks(Runnable action) Removes the specified Runnable from the message queue.
  • void removeOnAttachStateChangeListener(View.OnAttachStateChangeListener listener) Remove a listener for attach state changes.
  • void removeOnLayoutChangeListener(View.OnLayoutChangeListener listener) Remove a listener for layout changes.
  • void requestApplyInsets() Ask that a new dispatch of onApplyWindowInsets(WindowInsets) be performed.
  • void requestFitSystemWindows() This method was deprecated in API level 20. Use requestApplyInsets() for newer platform versions.
  • final boolean requestFocus(int direction) Call this to try to give focus to a specific view or to one of its descendants and give it a hint about what direction focus is heading.
  • final boolean requestFocus() Call this to try to give focus to a specific view or to one of its descendants.
  • boolean requestFocus(int direction, Rect previouslyFocusedRect) Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from.
  • final boolean requestFocusFromTouch() Call this to try to give focus to a specific view or to one of its descendants.
  • void requestLayout() Call this when something has changed which has invalidated the layout of this view.
  • void requestPointerCapture() Requests pointer capture mode.
  • boolean requestRectangleOnScreen(Rect rectangle) Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.
  • boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.
  • final void requestUnbufferedDispatch(MotionEvent event) Request unbuffered dispatch of the given stream of MotionEvents to this View.
  • static int resolveSize(int size, int measureSpec) Version of resolveSizeAndState(int, int, int) returning only the MEASURED_SIZE_MASK bits of the result.
  • static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) Utility to reconcile a desired size and state, with constraints imposed by a MeasureSpec.
  • boolean restoreDefaultFocus() Gives focus to the default-focus view in the view hierarchy that has this view as a root.
  • void restoreHierarchyState(SparseArray<Parcelable> container) Restore this view hierarchy's frozen state from the given container.
  • void saveHierarchyState(SparseArray<Parcelable> container) Store this view hierarchy's frozen state into the given container.
  • void scheduleDrawable(Drawable who, Runnable what, long when) Schedules an action on a drawable to occur at a specified time.
  • void scrollBy(int x, int y) Move the scrolled position of your view.
  • void scrollTo(int x, int y) Set the scrolled position of your view.
  • void sendAccessibilityEvent(int eventType) Sends an accessibility event of the given type.
  • void sendAccessibilityEventUnchecked(AccessibilityEvent event) This method behaves exactly as sendAccessibilityEvent(int) but takes as an argument an empty AccessibilityEvent and does not perform a check whether accessibility is enabled.
  • void setAccessibilityDelegate(View.AccessibilityDelegate delegate) Sets a delegate for implementing accessibility support via composition (as opposed to inheritance).
  • void setAccessibilityLiveRegion(int mode) Sets the live region mode for this view.
  • void setAccessibilityTraversalAfter(int afterId) Sets the id of a view after which this one is visited in accessibility traversal.
  • void setAccessibilityTraversalBefore(int beforeId) Sets the id of a view before which this one is visited in accessibility traversal.
  • void setActivated(boolean activated) Changes the activated state of this view.
  • void setAlpha(float alpha) Sets the opacity of the view to a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.
  • void setAnimation(Animation animation) Sets the next animation to play for this view.
  • void setAutoFillMode(int autoFillMode) Set auto-fill mode for the view.
  • void setBackground(Drawable background) Set the background to a given Drawable, or remove the background.
  • void setBackgroundColor(int color) Sets the background color for this view.
  • void setBackgroundDrawable(Drawable background) This method was deprecated in API level 16. use setBackground(Drawable) instead
  • void setBackgroundResource(int resid) Set the background to a given resource.
  • void setBackgroundTintList(ColorStateList tint) Applies a tint to the background drawable.
  • void setBackgroundTintMode(PorterDuff.Mode tintMode) Specifies the blending mode used to apply the tint specified by setBackgroundTintList(ColorStateList)} to the background drawable.
  • final void setBottom(int bottom) Sets the bottom position of this view relative to its parent.
  • void setCameraDistance(float distance) Sets the distance along the Z axis (orthogonal to the X/Y plane on which views are drawn) from the camera to this view.
  • void setClickable(boolean clickable) Enables or disables click events for this view.
  • void setClipBounds(Rect clipBounds) Sets a rectangular area on this view to which the view will be clipped when it is drawn.
  • void setClipToOutline(boolean clipToOutline) Sets whether the View's Outline should be used to clip the contents of the View.
  • void setContentDescription(CharSequence contentDescription) Sets the View's content description.
  • void setContextClickable(boolean contextClickable) Enables or disables context clicking for this view.
  • void setDrawingCacheBackgroundColor(int color) Setting a solid background color for the drawing cache's bitmaps will improve performance and memory usage.
  • void setDrawingCacheEnabled(boolean enabled) Enables or disables the drawing cache.
  • void setDrawingCacheQuality(int quality) Set the drawing cache quality of this view.
  • void setDuplicateParentStateEnabled(boolean enabled) Enables or disables the duplication of the parent's state into this view.
  • void setElevation(float elevation) Sets the base elevation of this view, in pixels.
  • void setEnabled(boolean enabled) Set the enabled state of this view.
  • void setFadingEdgeLength(int length) Set the size of the faded edge used to indicate that more content in this view is available.
  • void setFilterTouchesWhenObscured(boolean enabled) Sets whether the framework should discard touches when the view's window is obscured by another visible window.
  • void setFitsSystemWindows(boolean fitSystemWindows) Sets whether or not this view should account for system screen decorations such as the status bar and inset its content; that is, controlling whether the default implementation of fitSystemWindows(Rect) will be executed.
  • void setFocusable(boolean focusable) Set whether this view can receive the focus.
  • void setFocusable(int focusable) Sets whether this view can receive focus.
  • void setFocusableInTouchMode(boolean focusableInTouchMode) Set whether this view can receive focus while in touch mode.
  • void setFocusedByDefault(boolean isFocusedByDefault) Sets whether this View should receive focus when the focus is restored for the view hierarchy containing this view.
  • void setForeground(Drawable foreground) Supply a Drawable that is to be rendered on top of all of the content in the view.
  • void setForegroundGravity(int gravity) Describes how the foreground is positioned.
  • void setForegroundTintList(ColorStateList tint) Applies a tint to the foreground drawable.
  • void setForegroundTintMode(PorterDuff.Mode tintMode) Specifies the blending mode used to apply the tint specified by setForegroundTintList(ColorStateList)} to the background drawable.
  • void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) Set whether this view should have haptic feedback for events such as long presses.
  • void setHasTransientState(boolean hasTransientState) Set whether this view is currently tracking transient state that the framework should attempt to preserve when possible.
  • void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) Define whether the horizontal edges should be faded when this view is scrolled horizontally.
  • void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) Define whether the horizontal scrollbar should be drawn or not.
  • void setHovered(boolean hovered) Sets whether the view is currently hovered.
  • void setId(int id) Sets the identifier for this view.
  • void setImportantForAccessibility(int mode) Sets how to determine whether this view is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen.
  • void setKeepScreenOn(boolean keepScreenOn) Controls whether the screen should remain on, modifying the value of KEEP_SCREEN_ON.
  • void setKeyboardNavigationCluster(boolean isCluster) Set whether this view is a root of a keyboard navigation cluster.
  • void setLabelFor(int id) Sets the id of a view for which this view serves as a label for accessibility purposes.
  • void setLayerPaint(Paint paint) Updates the Paint object used with the current layer (used only if the current layer type is not set to LAYER_TYPE_NONE).
  • void setLayerType(int layerType, Paint paint) Specifies the type of layer backing this view.
  • void setLayoutDirection(int layoutDirection) Set the layout direction for this view.
  • void setLayoutParams(ViewGroup.LayoutParams params) Set the layout parameters associated with this view.
  • final void setLeft(int left) Sets the left position of this view relative to its parent.
  • void setLongClickable(boolean longClickable) Enables or disables long click events for this view.
  • void setMinimumHeight(int minHeight) Sets the minimum height of the view.
  • void setMinimumWidth(int minWidth) Sets the minimum width of the view.
  • void setNestedScrollingEnabled(boolean enabled) Enable or disable nested scrolling for this view.
  • void setNextClusterForwardId(int nextClusterForwardId) Sets the id of the view to use as the root of the next keyboard navigation cluster.
  • void setNextFocusDownId(int nextFocusDownId) Sets the id of the view to use when the next focus is FOCUS_DOWN.
  • void setNextFocusForwardId(int nextFocusForwardId) Sets the id of the view to use when the next focus is FOCUS_FORWARD.
  • void setNextFocusLeftId(int nextFocusLeftId) Sets the id of the view to use when the next focus is FOCUS_LEFT.
  • void setNextFocusRightId(int nextFocusRightId) Sets the id of the view to use when the next focus is FOCUS_RIGHT.
  • void setNextFocusUpId(int nextFocusUpId) Sets the id of the view to use when the next focus is FOCUS_UP.
  • void setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener listener) Set an View.OnApplyWindowInsetsListener to take over the policy for applying window insets to this view.
  • void setOnCapturedPointerListener(View.OnCapturedPointerListener l) Set a listener to receive callbacks when the pointer capture state of a view changes.
  • void setOnClickListener(View.OnClickListener l) Register a callback to be invoked when this view is clicked.
  • void setOnContextClickListener(View.OnContextClickListener l) Register a callback to be invoked when this view is context clicked.
  • void setOnCreateContextMenuListener(View.OnCreateContextMenuListener l) Register a callback to be invoked when the context menu for this view is being built.
  • void setOnDragListener(View.OnDragListener l) Register a drag event listener callback object for this View.
  • void setOnFocusChangeListener(View.OnFocusChangeListener l) Register a callback to be invoked when focus of this view changed.
  • void setOnGenericMotionListener(View.OnGenericMotionListener l) Register a callback to be invoked when a generic motion event is sent to this view.
  • void setOnHoverListener(View.OnHoverListener l) Register a callback to be invoked when a hover event is sent to this view.
  • void setOnKeyListener(View.OnKeyListener l) Register a callback to be invoked when a hardware key is pressed in this view.
  • void setOnLongClickListener(View.OnLongClickListener l) Register a callback to be invoked when this view is clicked and held.
  • void setOnScrollChangeListener(View.OnScrollChangeListener l) Register a callback to be invoked when the scroll X or Y positions of this view change.
  • void setOnSystemUiVisibilityChangeListener(View.OnSystemUiVisibilityChangeListener l) Set a listener to receive callbacks when the visibility of the system bar changes.
  • void setOnTouchListener(View.OnTouchListener l) Register a callback to be invoked when a touch event is sent to this view.
  • void setOutlineProvider(ViewOutlineProvider provider) Sets the ViewOutlineProvider of the view, which generates the Outline that defines the shape of the shadow it casts, and enables outline clipping.
  • void setOverScrollMode(int overScrollMode) Set the over-scroll mode for this view.
  • void setPadding(int left, int top, int right, int bottom) Sets the padding.
  • void setPaddingRelative(int start, int top, int end, int bottom) Sets the relative padding.
  • void setPivotX(float pivotX) Sets the x location of the point around which the view is rotated and scaled.
  • void setPivotY(float pivotY) Sets the y location of the point around which the view is rotated and scaled.
  • void setPointerIcon(PointerIcon pointerIcon) Set the pointer icon for the current view.
  • void setPressed(boolean pressed) Sets the pressed state for this view.
  • final void setRevealOnFocusHint(boolean revealOnFocus) Sets this view's preference for reveal behavior when it gains focus.
  • final void setRight(int right) Sets the right position of this view relative to its parent.
  • void setRotation(float rotation) Sets the degrees that the view is rotated around the pivot point.
  • void setRotationX(float rotationX) Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
  • void setRotationY(float rotationY) Sets the degrees that the view is rotated around the vertical axis through the pivot point.
  • void setSaveEnabled(boolean enabled) Controls whether the saving of this view's state is enabled (that is, whether its onSaveInstanceState() method will be called).
  • void setSaveFromParentEnabled(boolean enabled) Controls whether the entire hierarchy under this view will save its state when a state saving traversal occurs from its parent.
  • void setScaleX(float scaleX) Sets the amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width.
  • void setScaleY(float scaleY)
    Sets the amount that the view is scaled in Y around the pivot point, as a proportion of the view's unscaled width.
  • void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade)
    Define the delay before scrollbars fade.
  • void setScrollBarFadeDuration(int scrollBarFadeDuration)
    Define the scrollbar fade duration.
  • void setScrollBarSize(int scrollBarSize)
    Define the scrollbar size.
  • void setScrollBarStyle(int style)
    Specify the style of the scrollbars.
  • void setScrollContainer(boolean isScrollContainer)
    Change whether this view is one of the set of scrollable containers in its window.
  • void setScrollIndicators(int indicators, int mask)
    Sets the state of the scroll indicators specified by the mask.
  • void setScrollIndicators(int indicators)
    Sets the state of all scroll indicators.
  • void setScrollX(int value)
    Set the horizontal scrolled position of your view.
  • void setScrollY(int value)
    Set the vertical scrolled position of your view.
  • void setScrollbarFadingEnabled(boolean fadeScrollbars)
    Define whether scrollbars will fade when the view is not scrolling.
  • void setSelected(boolean selected)
    Changes the selection state of this view.
  • void setSoundEffectsEnabled(boolean soundEffectsEnabled)
    Set whether this view should have sound effects enabled for events such as clicking and touching.
  • void setStateListAnimator(StateListAnimator stateListAnimator)
    Attaches the provided StateListAnimator to this View.
  • void setSystemUiVisibility(int visibility)
    Request that the visibility of the status bar or other screen/window decorations be changed.
  • void setTag(int key, Object tag)
    Sets a tag associated with this view and a key.
  • void setTag(Object tag)
    Sets the tag associated with this view.
  • void setTextAlignment(int textAlignment)
    Set the text alignment.
  • void setTextDirection(int textDirection)
    Set the text direction.
  • void setTooltipText(CharSequence tooltipText)
    Sets the tooltip text which will be displayed in a small popup next to the view.
  • final void setTop(int top)
    Sets the top position of this view relative to its parent.
  • void setTouchDelegate(TouchDelegate delegate)
    Sets the TouchDelegate for this View.
  • final void setTransitionName(String transitionName)
    Sets the name of the View to be used to identify Views in Transitions.
  • void setTranslationX(float translationX)
    Sets the horizontal location of this view relative to its left position.
  • void setTranslationY(float translationY)
    Sets the vertical location of this view relative to its top position.
  • void setTranslationZ(float translationZ)
    Sets the depth location of this view relative to its elevation.
  • void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)
    Define whether the vertical edges should be faded when this view is scrolled vertically.
  • void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) Define whether the vertical scrollbar should be drawn or not.
  • void setVerticalScrollbarPosition(int position) Set the position of the vertical scroll bar.
  • void setVisibility(int visibility) Set the visibility state of this view.
  • void setWillNotCacheDrawing(boolean willNotCacheDrawing) When a View's drawing cache is enabled, drawing is redirected to an offscreen bitmap.
  • void setWillNotDraw(boolean willNotDraw) If this view doesn't do any drawing on its own, set this flag to allow further optimizations.
  • void setX(float x) Sets the visual x position of this view, in pixels.
  • void setY(float y) Sets the visual y position of this view, in pixels.
  • void setZ(float z) Sets the visual z position of this view, in pixels.
  • boolean showContextMenu() Shows the context menu for this view.
  • boolean showContextMenu(float x, float y) Shows the context menu for this view anchored to the specified view-relative coordinate.
  • ActionMode startActionMode(ActionMode.Callback callback, int type) Start an action mode with the given type.
  • ActionMode startActionMode(ActionMode.Callback callback) Start an action mode with the default type TYPE_PRIMARY.
  • void startAnimation(Animation animation) Start the specified animation now.
  • final boolean startDrag(ClipData data, View.DragShadowBuilder shadowBuilder, Object myLocalState, int flags) This method was deprecated in API level 24. Use startDragAndDrop() for newer platform versions.
  • final boolean startDragAndDrop(ClipData data, View.DragShadowBuilder shadowBuilder, Object myLocalState, int flags) Starts a drag and drop operation.
  • boolean startNestedScroll(int axes) Begin a nestable scroll operation along the given axes.
  • void stopNestedScroll() Stop a nested scroll in progress.
  • String toString() Returns a string representation of the object.
  • void unscheduleDrawable(Drawable who, Runnable what) Cancels a scheduled action on a drawable.
  • void unscheduleDrawable(Drawable who) Unschedule any events associated with the given Drawable.
  • final void updateDragShadow(View.DragShadowBuilder shadowBuilder) Updates the drag shadow for the ongoing drag and drop operation.
  • boolean willNotCacheDrawing() Returns whether or not this View can cache its drawing or not.
  • boolean willNotDraw() Returns whether or not this View draws on its own.

获取上级View的方法汇总

getParent()                                                    //获取上一级View
getRootView                                                    //获取跟布局
getWindow().getDecorView()                                     
findViewById(android.R.id.content)
((ViewGroup)findViewById(android.R.id.content)).getChildAt(0)

方法介绍

20171012150781516882260.png
20171012150781516882260.png

getRootView特例

布局(R.layout.list_empty):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:text="暂无数据" />
</RelativeLayout>

代码:

    final View view = View.inflate(this, R.layout.list_empty, null);
    final TextView name = (TextView) view.findViewById(R.id.name);
    System.out.println("before View.inflate name getParent " + name.getParent());
    System.out.println("before View.inflate name getRootView " + name.getRootView());
    addContentView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
    System.out.println("after View.inflate name getParent " + name.getParent());
    System.out.println("after View.inflate name getRootView " + name.getRootView());
结果:
before View.inflate name getParent android.widget.RelativeLayout{3d679e31 V.E..... ......ID 0,0-0,0}
before View.inflate name getRootView android.widget.RelativeLayout{3d679e31 V.E..... ......ID 0,0-0,0}
after View.inflate name getParent android.widget.RelativeLayout{3d679e31 V.E..... ......ID 0,0-0,0}
after View.inflate name getRootView com.android.internal.policy.impl.MultiPhoneWindow$MultiPhoneDecorView{c535bb V.E..... R.....ID 0,0-0,0}

结论:如果View在代码中通过View.inflate实例化,在没有添加到显示界面前,getRootView获得的是Xml的根布局。添加后getRootView获得的是MultiPhoneDecorView。

使用场景

用途:状态栏、标题栏、键盘的高度

注意:以下代码不能在onCreate里面使用,否则获取的高度为0,你可以放在onWindowFocusChanged等等

状态栏高度:

getDecorViewgetWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 于是,我们就可以算出状态栏的高度了。

Rect frame = new Rect();  
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
int statusBarHeight = frame.top;

标题栏高度

findViewById(Android.R.id.content)是不包括标题栏的,我们可以通过它获取标题栏的高度。

int contentTop = findViewById(android.R.id.content).getTop();  
//statusBarHeight是上面所求的状态栏的高度  
int titleBarHeight = contentTop - statusBarHeight;

键盘高度

  • 键盘没打开时获取android.R.id.content的可见区域高度height1,
  • 键盘打开时再获取android.R.id.content的可见区域高度height2,
  • 键盘的高度height1-height2
private View globalView;
private int firstHeight;
private boolean isFirst = true;

globalView = findViewById(android.R.id.content);
globalView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        Rect rect = new Rect();
        globalView.getWindowVisibleDisplayFrame(rect);
        if (isFirst) {
            isFirst = false;
            firstHeight = rect.height();
        } else {
            int height = rect.height();
            if (height < firstHeight) {
                System.out.println("键盘打开 " + (firstHeight - height));
            } else {
                System.out.println("键盘关闭 ");
            }
        }
    }
});