开发过程中,获取view是通常是通过findViewById来获取,然后强制转化为对应的TextView、Button、ImageView等,这样强制转化很麻烦。其实我们可以通过java中的泛型机制来避免这个强转过程,我们可以在项目中的BaseActivity中添加如下的方法:
public final <E extends View> E getView(int id){
try {
return (E)findViewById(id);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
其中方法加final是防止该方法在子类中被重写。然后在Activity中可以如下获取view:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtView = getView(R.id.txt_view1);
txtView .setText("泛型获取view测试文本");
Button btn = getView(R.id.btn_button1);
btn.setText("泛型获取view测试按钮");
}