Android开发中的findViewById(R.id.textView)

Posted iblade

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发中的findViewById(R.id.textView)相关的知识,希望对你有一定的参考价值。

这里写图片描述
如果已经敲了几年代码,这样写会不会显得太Low
以下提供几种改良办法:

一、首先提到反射:

反射不太好,性能开销大,官方文档说过的。不是迫不得已不用反射,直接略过。附上副作用的官方文档:“Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
Performance OverheadBecause reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.Security RestrictionsReflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.Exposure of InternalsSince reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.“

二、中国特色法:(逗比法,仅限逗比参考,慎用)

介绍一种我在知乎上搜到的野路子,绝壁是跨界运用大神,直接上图:这里写图片描述

三、说说,我是怎么用的

方法一:(推荐使用)

这里写图片描述

定义一个f(int id)方法:

private <T extends View> T f(int viewId) {
        return (T) findViewById(viewId);
    }
  //<T extends View>可以直接写成<T>

方法二:快捷键(可阅读性最好)

fbc+Tab
①局部变量时候.var

这里写图片描述
②全局变量时候.field
这里写图片描述
按下Enter后选择第二个
这里写图片描述
此时命名控件
这里写图片描述

另外Toast常用快捷键
这里写图片描述
按下Enter键,输入吐司内容即可
这里写图片描述

以上是关于Android开发中的findViewById(R.id.textView)的主要内容,如果未能解决你的问题,请参考以下文章

如何获取android安卓控件EditText中的内容

findViewById(R.id.videoView) 在片段中返回 Null (Android Studio)

android中的多个警报

Android -- 从 findViewById(R...) 分配的 SurfaceView 将不允许访问自定义字段

findViewById(android.R.id.content) 可以为 Snackbars 返回 null 吗?

Android:findViewById 给了我错误的指针?