简体   繁体   中英

How to make two different Constructors in the same Class - Android

i think that this can be done, but maybe im wrong (Im sure im wrong). I have this adapter that sometimes uses a List of Class1 and in other moments uses a list of Class2. So, can i do TWO differents constructors where un the first one i use List1 and in the other one i use the List2?

public class SpinnerAdapter extends BaseAdapter {

private List<String> listaDeTexto;
private Activity activity;
private LayoutInflater layoutInflater;
private List<MetodoDePago> listaMetodosDePago;
private List<Banco> listaDeBancos;

public SpinnerAdapter(List<String> listaDeTexto, Activity activity, List<MetodoDePago> listaMetodosDePago) {
    this.listaDeTexto = listaDeTexto;
    this.activity = activity;
    this.layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.listaMetodosDePago = listaMetodosDePago;
}

public SpinnerAdapter(List<String> listaDeTexto, Activity activity, List<Banco> listaDeBancos) {
    this.listaDeTexto = listaDeTexto;
    this.activity = activity;
    this.layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.listaDeBancos = listaDeBancos;
}

@Override
public int getCount() {
    return listaDeTexto.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    if (convertView == null){
        view = layoutInflater.inflate(R.layout.spinner_custom,null);
    }
    TextView textView = view.findViewById(R.id.textViewSpinner);
    textView.setText(listaDeTexto.get(position));

    ImageView imageView = view.findViewById(R.id.imgViewSpinner);
    Glide.with(view)
            .load(listaMetodosDePago.get(position).getThumbnail())
            .into(imageView);

    return view;
}

}

Due to type erasure in Java, you are basically declaring two constructors which look like, SpinnerAdapter(List l1, Activity a, List l2) { } to Java.

A simple solution would be to create one constructor and add a type argument. So, something like, SpinnerAdapter(List l1, Activity a, List l2, int type) { } .

You can then check the type value in the constructor and the getView(...) method to initialize your variables as needed.

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