Omeed Totakhel Omeed Totakhel - 11 months ago 45
Java Question

Create a function for creating variables (EditText, Button) Java Android

Is it possible to short the code of creating a EditText in java.


EditText input1 = (EditText) findViewById(;

instead of writing the whole code can we wrap it to a function liek

public static CreateItem(String Type, String name, String id) {
return Type name = (Type) findViewById( + id)
Input1 = CreateItem(EditText, Input1, InputField);
Input2 = CreateItem(EditText, Input2, InputField2);

Answer Source

You should use this:

  @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
  public static <T extends View> T findById(View view, int id) {
    return (T) view.findViewById(id);

and this :

  @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
  public static <T extends View> T findById(Activity activity, int id) {
    return (T) activity.findViewById(id);


EditText input = findById(this,;