1.通常我们通过findViewById得到View都要加个强制转换,这样感觉很麻烦,现在我们可以在BaseActivity加上如下方法通过泛型来有减少书写:
@SuppressWarnings(“unchecked”) public final <E extends View> E getView (int id) { try { return (E) findViewById(id); } catch (ClassCastException e) { Log.e(TAG, “Could not cast View to concrete class.”, e); throw e; } }
2.我们在activity中就可以通过getView来获得控件了。
TextView textView = getView(R.id.textview); Button button = getView(R.id.button); ImageView image = getView(R.id.imageview); //注意:如果级联调用getView 函数,则还是需要Cast转换 private static void myView (ImageView img) { ... } @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); // myView(getView(R.id.imageview)); //这样无法通过编译 myView((ImageView) getView(R.id.imageview)); //需要Cast转换才可以 }