文章目录
  1. 1. 第一种
  2. 2. 第二种
  3. 3. 第三种

在 Android 获取一个 View 一般都是通过如下方式:

1
TextView textView = (TextView) findViewById(R.id.textview);

相信大家都写过无数次 findViewById 了吧,每次都要 Cast 一下是否很不爽啊。今天就来介绍三种简便的方法避免这种 Cast。

第一种

在项目基类 BaseActivity 中添加如下函数:

1
2
3
4
5
6
7
8
9
@SuppressWarnings(“unchecked”)
public final <E extends View> E getView (int id) {
try {
return (E) findViewById(id);
} catch (ClassCastException ex) {
Log.e(TAG, “Could not cast View to concrete class.”, ex);
throw ex;
}
}

然后就可以通过如下方式获取 view 了:

1
2
3
TextView textView = getView(R.id.textview);
Button button = getView(R.id.button);
ImageView image = getView(R.id.imageview);

注意:如果级联调用 getView 函数,则还是需要 Cast 的,如下示例:

1
2
3
4
5
6
7
8
9
private static void myMethod (ImageView img) {
//Do nothing
}
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myMethod(getView(R.id.imageview)); //这样无法通过编译
myMethod((ImageView) getView(R.id.imageview)); //需要Cast才可以
}

第二种

第一种方法只在Activity里有效,其实我们经常在其他View或者Fragment里也常用findViewById方法,当然你可以把上述方法copy一遍,但是这违反了面向对象基本的封装原则,有大神封装了一个ViewFinder类,具体代码可以见我Gist上的文件ViewFinder.java, 使用的时候你只需要在你的Activity或者View里这样使用:

1
2
ViewFinder finder = new ViewFinder(this);
TextView textView = finder.find(R.id.textview);

第三种

前两种方法本质上是利用了泛型,还有一种利用注解的方式,使用起来更方便,不仅省事的处理了 findViewById ,甚至包括 setOnClickListener 这种方法也能很方便的调用,具体见我这篇博客 ButterKnife–View注入框架

注意:如果你是使用的Eclipse引用该library,你需要参考这里 Eclipse Configuration 做一些配置,否则会运行出错。


本文地址 http://94275.cn/2014/10/14/android-find-view/ 作者为 Zhenguo

author:Zhenguo
Author: Zhenguo      Blog: 94275.cn/     Email: jinzhenguo1990@gmail.com
I have almost 10 years of application development experience and have a keen interested in the latest emerging technologies. I use my spare time to turn my experience, ideas and love for IT tech into informative articles, tutorials and more in hope to help others and learn more.
文章目录
  1. 1. 第一种
  2. 2. 第二种
  3. 3. 第三种
返回顶部