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(R.id.exampleTextView);
ImageView imageView = (ImageView) findViewById(R.id.exampleImageView);
Button button = (Button) findViewById(R.id.exampleButton);

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);
}
@SuppressWarnings("unchecked")
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(R.id.exampleTextView);
ImageView imageView = getView(R.id.exampleImageView);
Button button = getView(R.id.exampleButton);

Reference:http://ysl-paradise.blogspot.tw/2014/04/activitygetview.html

Comments

comments powered by Disqus