使用BaseAdapter for Spinner

时间:2012-11-05 12:58:43

标签: android android-layout android-widget android-spinner

任务是使用POJO对象的值填充微调器。在此之前,我正在使用正常的String值和BaseAdapter进行检查。

我在活动组中有活动。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_date_filter);

    startMonth = (Spinner) findViewById(R.id.startMonth);

    startMonth.setAdapter(new CustomSpinnerAdapter(getParent(), new ArrayList<String>()));
}

layout_spinner_row.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/spinnerValue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

我的适配器类是:

public class CustomSpinnerAdapter extends BaseAdapter{ 

private List<String> alertList;
private LayoutInflater mInflater;

public CustomSpinnerAdapter(Context context, Object results) {
    alertList = (List<String>) results;
    //just check if it works. 
   //in real, actual object fits in
   alertList.add("January");
    alertList.add("Feburary");
    alertList.add("March");
    mInflater = LayoutInflater.from(context);
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.layout_spinner_row, null);
        holder = new ViewHolder();
        holder.spinnerValue = (TextView) convertView.findViewById(R.id.spinnerValue);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.spinnerValue.setText(alertList.get(position));
    return convertView;
}




static class ViewHolder {
    TextView spinnerValue; //spinner name
}
}

当我点击微调器时,我收到以下错误:

E/AndroidRuntime(1686): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@4135fa38 is not valid; is your activity running?

我找不到任何有效的答案。有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分:3)

您需要将视图设置为相应的视图对象,以使微调器工作。 为此,您需要更改活动的创建:

View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.activity_date_filter, null); 
this.setContentView(viewToLoad); 

完整说明: http://developer.android.com/reference/android/view/LayoutInflater.html

答案 1 :(得分:1)

从您的适配器代码中,我可以说您尚未初始化LayoutInflater ,如果不这样做,您就会尝试对布局进行充气。所以在你的构造函数中,使用:

 this.mInflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);