我是 Android Studio 的新手,我想快速访问按钮、 ImageView 、 TextView 等 View 。
到目前为止,我知道 findViewById
方法,这就是我为创建对 View 的轻松访问所做的工作:
Button btn1, btn2, btn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn1=(Button)findViewById(R.id.btn1);
this.btn2=(Button)findViewById(R.id.btn2);
this.btn3=(Button)findViewById(R.id.btn3);
}
//then I simply use my defined vars
虽然它有效,但必须编写所有这些代码(或者每次都必须使用 findViewById
,使用获取 id 的繁琐方式并仍然添加转换)仍然很无聊。
这真的是最好的方法吗?
最佳答案
您可以查看像 Butterknife 这样的库 http://jakewharton.github.io/butterknife/ .
它可以防止您编写样板代码 - 只需注入(inject) View 即可。 你可以将它与这个 Android Studio 插件结合起来: https://plugins.jetbrains.com/plugin/7369-android-butterknife-zelezny
通过此设置,注入(inject) View 非常简单和快速。
此外,您还可以查看“数据绑定(bind)”之类的主题 https://developer.android.com/topic/libraries/data-binding/index.html 为您定义 View 也是一种好方法。
关于java - Android Studio - 获取 Activity View 实例的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45092435/