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键,输入吐司内容即可
这里写图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值