自动引用Android布局组件

时间:2013-05-29 04:03:07

标签: java android reflection

我觉得我在Android开发中不断重复这种模式:

在布局中声明UI组件

<SeekBar
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/seekTriggerFreq"/>

使用findViewById获取引用并将其转换为

SeekBar seekTriggerFreq = (SeekBar)findViewById(R.id.seekTriggerFreq);

对于一些组件来说没什么大不了的,但是在十几个组件之后它变得很麻烦。这可以使用反射,Maven或Ant等自动化吗?也许是一个构建脚本,为您生成一个带有静态引用的类?

更新: 所需的行为类似于Visual Studio为其设计人员工作的方式。 winforms,xaml和asp.net中的控件都可以使用,无需手动获取引用。我懒吗?是。但我也知道,我自动化程度越高,我的错误就越少。

2 个答案:

答案 0 :(得分:1)

AndroidAnnotations是一个免费的开源库,可以取代

SeekBar seekTriggerFreq = (SeekBar)findViewById(R.id.seekTriggerFreq);

@ViewById
SeekBar seekTriggerFreq;

还有更多关于如何在其网站上用注释替换样板代码的例子。

答案 1 :(得分:0)

宣布...... SeekBar seekTriggerFreq; //全球宣言

然后初始化它.. seekTriggerFreq =(SeekBar)findViewById(R.id.seekTriggerFreq); //在任何第一个调用函数中,以便初始化.. 并根据需要多次使用“seekTriggerFreq”