通过泛型来简化findViewById

原文:http://www.cnblogs.com/tianzhijiexian/p/4254634.html 

我们一般写findViewById都要加个强制转换,感觉很麻烦,现在你可以在你的BaseActivity中写入如下方法:

@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;
    }
}

之后你在你的代码中就可以通过getView来获得控件了。

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才可以
}

其他的方法请参考:http://www.stormzhang.com/android/androidtips/2014/08/24/android-viewfinder/