简体   繁体   中英

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 like:

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

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

看起来您需要此库: Android Buttknife

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM