在不是活动的类上使用“this”的Android上下文

时间:2015-04-07 11:08:16

标签: android this android-context

我创建了以下类,用两种不同的视图填充listView。其中一种包含一个微调器,我试图填充包含在包中的Arraylists(每个微调器一个)。我正在处理的问题是ArrayAdapter构造函数,它显然存在我使用的上下文的问题(" this")。有什么想法吗?

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 个答案:

答案 0 :(得分:1)

@ρяσѕρєяK写道:

  

使用view.getContext()parent.getContext()代替this