Android context using “this” on class that is not an activity

大城市里の小女人 提交于 2019-12-13 03:08:20

问题


I created the following class to populate a listView with two different kinds of views. One of the two kinds contain is a spinner, which I'm trying to populate with Arraylists (one for each spinner) contained in the bundle. The problem I'm dealing with is the ArrayAdapter constructor, which clearly has a problem with the context I'm using ("this"). Any ideas?

public class InsertAdapter extends BaseAdapter {

private static final int OWN_KEY = 0;
private static final int FOREIGN_KEY = 1;
private ArrayList<ColumnProperties> columns = new ArrayList<ColumnProperties>();
private Bundle spinner_strings;

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position){
    return (columns.get(position).isForeign()) ? FOREIGN_KEY : OWN_KEY;
}

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

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

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

public View getView(int position, View view, ViewGroup parent) {
    int type = getItemViewType(position);
    if (view == null) {
        LayoutInflater inflater =
                LayoutInflater.from(parent.getContext());
        if(type==0) {
            view = inflater.inflate(
                    R.layout.text_field, parent, false);
        }else{
            view = inflater.inflate(
                    R.layout.text_spinner, parent, false);
        }
    }

    ColumnProperties column = columns.get(position);

    TextView col_name = (TextView) view.findViewById(R.id.column_name);
    col_name.setText(column.getName());

    if(type==FOREIGN_KEY){
        Spinner spinner = (Spinner) view.findViewById(R.id.foreign_keys);
        ArrayList<String> spinner_list = spinner_strings.getStringArrayList(column.getName());
        //List<String> list;

        ArrayAdapter spinner_adapter = new ArrayAdapter(this , android.R.layout.simple_spinner_item,spinner_list);
        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(spinner_adapter);
    }

    return view;
}

public void getSpinnerStrings(Bundle spinner_strings){
    this.spinner_strings = spinner_strings;
}

}

回答1:


@ρяσѕρєя K wrote:

Use view.getContext() or parent.getContext() instead of this



来源:https://stackoverflow.com/questions/29490118/android-context-using-this-on-class-that-is-not-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!