开发者

Trying to lazy load android view using generics

I have an application and in one of my activities I created a base activity that contains some helper methods that derived classes can use.

I have a method that lazy loads views, here is the code

    protected <T extends View> void loadView(T view, int id) {
    if(view == null){
        view = (T)findViewById(id);
    }

In my derived class I call it as such.

private Button btnAddAlarm
...
@Override
public void onCreate(Bundle savedInstanceState) 开发者_如何转开发{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.timer_list);

    loadView(btnDeleteAlarm, R.id.btnDeleteAlarm); //the view in the helper method loaded fine
    btnDeleteAlarm.setEnabled(false); //Null pointer exception!

the problem is that btnDeleteAlarm is null after it exits from the function, even though the reference is passed in.

I haven't touched java in a while but if I remember the basics this shouldn't happen when passing references.


You never assigned something to btnDeleteAlarm. In java, methods always copy their arguments, so loadView gets a copy of the reference btnDeleteAlarm and maybe changes the copy, but it wont change btnDeleteAlarm. You could let your loadView method return the "view" and assign it in the onCreate method to btnDeleteAlarm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜