Android ViewFinder

在Android获取一个View通常都是经过以下方式:html

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

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

第一种

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

@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了:git

TextView textView = getView(R.id.textview);
Button button = getView(R.id.button);
ImageView image = getView(R.id.imageview);
注意:若是级联调用getView 函数,则仍是须要Cast的,以下示例:
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里这样使用:github

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

第三种

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

注意:若是你是使用的Eclipse引用该library,你须要参考这里Eclipse Configuration作一些配置,不然会运行出错。eclipse

相关文章
相关标签/搜索