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鍵,輸入吐司內容即可
這里寫圖片描述


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com