Omeed Totakhel Omeed Totakhel - 2 months ago 6
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.

Example

EditText input1 = (EditText) findViewById(R.id.InputField);


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(R.id. + id)
}
Input1 = CreateItem(EditText, Input1, InputField);
Input2 = CreateItem(EditText, Input2, InputField2);

Answer

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);
  }

usage:

EditText input = findById(this, R.id.InputField);