Search code examples
androidfindviewbyidbutterknife

Bind views automatically by name


Writing boilerplate code always bothers me. One of these things in Android is binding views:

TextView email;
TextView password;
//...

private bindViews() {
    email = (TextView) findViewById(R.id.email);
    password = (TextView) findViewById(R.id.password);
    //...
}

Which I think could be made better.

Recently I found out about ButterKnife library and I loved it. It makes code less:

@BindView(R.id.email) TextView email;
@BindView(R.id.password) TextView password;
//...

ButterKnife.bind(this);

But the thing is that we usually name our views match their ids. For example both xml id and java field name is password. (And also convert snake-casing to camel-casing). So I was thinking that theoretically the id part could also be removed and the code be shortened to something like this:

@BindView TextView email;
@BindView TextView password;
//...

bind(this);

Is there such solution? If there isn't, would it be useful and viable? Because I'd like to create it, if there's not.


Solution

  • To my knowledge there isn't anything like that. But ButterKnife is actively worked on and has a pretty big following. I personally wouldn't switch away from that just to make my code slightly less verbose.

    It'd still be a pretty cool exercise to do I think. Could fork ButterKnife and try to get that feature merged in. It'd be a pretty big achievement to contribute to one of Jake Wharton's libraries.

    For what this is worth, you might like LoganSquare. It's a JSON Parser that does basically the same thing you're describing with Annotations. It's also very fast. Here's an example of using it:

    @JsonObject
    public class User{
        // Will infer JSON key based off variable's name
        @JsonField
        public String name;
    
        // Can specify a key's name too if you want like this 
        @JsonField(name="date_of_birth")
        public long dateOfBirth;
    
        // LoganSquare requires a default constructor like this
        public User(){}
    }