Moon Light Box

Time is Money

Android - Clean Code 1

| Comments

We always write this statement. And it is difficult to read.

TextView textView = (TextView) findViewById(;
ImageView imageView = (ImageView) findViewById(;
Button button = (Button) findViewById(;

Due to those components inherit android.view.View, we can use this method to clean code.

public final <E extends View> E getView(int id) {
    return (E) findViewById(id);
protected <E extends View> E getView(int viewId) {
    View view = sparseArray.get(viewId);
    if (view == null) {
        view = contentView.findViewById(viewId);
        sparseArray.put(viewId, view);
    return (E) view;

Then your code will become this. So clear! HaHa.

TextView textView = getView(;
ImageView imageView = getView(;
Button button = getView(;



comments powered by Disqus