Spinner getSelectedView()为null

时间:2015-10-28 16:01:17

标签: android android-spinner

我有一个微调器,它有6个项目,我可以看到它们。当我调用spinner.getSelectedView()时,它总是为空

知道为什么吗?

sortSpinner.setSelection(2);
CheckedTextView v = (CheckedTextView) sortSpinner.getSelectedView(); //crash null pointer
v.setChecked(true);

编辑:

我正在为微调器的适配器扩展ArrayAdapter

public class CustomSpinnerAdapter extends ArrayAdapter<String> {
    private Context context;
    private int layoutResourceId;
    private ArrayList<String> objects;

    public CustomSpinnerAdapter(Context ctx, int layoutResourceId,
            ArrayList<String> placeTypes) {
        super(ctx, layoutResourceId, placeTypes);
        this.context = ctx;
        this.layoutResourceId = layoutResourceId;
        this.objects =placeTypes;
    }

    @Override
    public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
        return getCustomView(position, cnvtView, prnt);
    }

    @Override
    public View getView(int pos, View cnvtView, ViewGroup prnt) {
        return getCustomView(pos, cnvtView, prnt);
    }

    class ViewHolderItem {
        TextView title;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        ViewHolderItem viewHolder;

        if (convertView == null) {

            // inflate the layout
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            convertView = inflater.inflate(layoutResourceId, parent, false);
            viewHolder = new ViewHolderItem();
            viewHolder.title = (TextView) convertView.findViewById(R.id.title);
            //Utils.setFontRobotLight(context, viewHolder.title);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolderItem) convertView.getTag();
        }
        String str = objects.get(position);
        viewHolder.title.setText(str);

        return convertView;
    }
}

 ArrayList<String> sortList = new ArrayList<String>(Arrays.asList(sortArr));
 CustomSpinnerAdapter sortAdapter = new CustomSpinnerAdapter(this, R.layout.custom_spinner_adapter_view_red,
                    sortList);
 sortSpinner.setAdapter(sortAdapter);

堆栈跟踪错误:

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {my.activity.name}:java.lang.NullPointerException:   尝试调用虚方法&#39; void   android.widget.CheckedTextView.setChecked(布尔值)&#39;在null对象上   参考

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckedTextView.setChecked(boolean)' on a null object reference
my.package.name.setSort(MyActivity.java:555)
my.package.name.onCreate(MyActivity.java:413)
android.app.Activity.performCreate(Activity.java:5990)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)

第55行是v.setChecked(true)

0 个答案:

没有答案