Skip to content

Instantly share code, notes, and snippets.

@StefMa
Last active August 29, 2015 14:26
Show Gist options
  • Save StefMa/1a7668fb7874e863c2e9 to your computer and use it in GitHub Desktop.
Save StefMa/1a7668fb7874e863c2e9 to your computer and use it in GitHub Desktop.
FindView class to remove the ugly casting of Android Views

FindView helper class


What is it?

This is a simple helper class to casting the Views of your layout file in your Activity or Fragment.


Why?

Normally you get your layout Views like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splashscreen);

    TextView tv = (TextView) findViewById(R.id.textview)
}

You need to casting all the views in the "right" view, when needed. That is ugly!


How to use?

With theses static helper class you can directly get your View you want.

For example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splashscreen);

    TextView tv = FindView.getView(this, R.id.textview)
}

So put the FindView class in your Utils package and use it like a pro ;)


Woha, more to know?

#HappyCoding

public class FindView {
public static <V extends View> V getView(Activity activity, int id) {
View rootView = activity.getWindow().getDecorView().getRootView();
return (V) rootView.findViewById(id);
}
public static <V extends View> V getView(Fragment fragment, int id) {
View rootView = fragment.getView();
if (rootView != null) {
return (V) rootView.findViewById(id);
} else {
throw new UnsupportedOperationException("Fragments rootview is null");
}
}
public static <V extends View> V getView(View rootView, int id) {
return (V) rootView.findViewById(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment