xUtils 工具包的简介在上一篇文章中已经说了,今天来简单介绍一下它的ViewUtils模块。该模块主要为我们简化了界面控件的定义及事件绑定,使用标签形式简少了冗余代码。
一、ViewUtils使用方法
完全注解方式就可以进行UI绑定和事件绑定。
无需findViewById和setClickListener等
二、示例
下面的示例展示了怎样使用ViewUtils来绑定控件及点击事件,点击按钮时,对文本框进行赋值操作。
1. 定义布局文件,定义一个按钮及文本框
<Button
android:id="@+id/btn_httptest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/http_test" />
<TextView
android:id="@+id/txt_test"
android:layout_below="@id/btn_httptest"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
2. 在对应的Activity代码中进行修改,如下所示:
public class MainActivity extends Activity {
@ViewInject(R.id.txt_test)
private TextView txt_test;
@OnClick(R.id.btn_httptest)
public void btnHttpTestClick(View arg0) {
txt_test.setText("Hello World!");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewUtils.inject(this);
}
}
如上所示,通过ViewInject标签进行控件绑定,不需要再写findViewById的代码,其中R.id.txt_test是控件ID。
通过OnClick标签来进行事件绑定,其中R.id.btn_httptest是要绑定的事件名称。ViewUtils模块支持大部分的事件绑定,这里只列举了最常用的。
注意需要在OnCreate的代码中添加ViewUtils.inject(this);来进行初始化,通过此行代码来进行相关内容绑定。
关于ViewUtils模块的详细操作请参考相关文档,这里只做简单介绍。