在Spinner上设置选择崩溃布局

时间:2015-10-05 19:42:42

标签: android spinner

我有一个非常简单的布局,里面有Spinner,它附有我自己的适配器。

MyAdapter myAdap = new MyAdapter();
mySpinner.setAdapter(myAdap);

适配器有两个项目(来自调试器):

myAdap.getCount() = 2

当我将选择设置为1时(0有效),

mySpinner.setSelection(1);

应用程序崩溃:

10-05 19:37:17.122 19899-19899/nl.example.demo E/test: Exception 10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime: FATAL EXCEPTION: main 
10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime: Process: example.demo, PID: 19899 10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime: java.lang.NullPointerException 
10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime:     at android.widget.TextView.makeNewLayout(TextView.java:6151) 
10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime:     at android.widget.TextView.onMeasure(TextView.java:6427) 
10-05 19:37:17.142 19899-19899/nl.example.demo E/AndroidRuntime:     at android.view.View.measure(View.java:16643)
[..]

奇怪的是,这可以在另一款具有相同版本Android的手机上使用,但屏幕更小。

MyAdapter如下:

public class MyAdapter extends ArrayAdapter<String> {
    static ArrayList<String> methods = null;
    private LayoutInflater mInflater;

    public MyAdapter(Context ctx) {
        super(ctx, 0);
        mInflater = LayoutInflater.from(ctx);
        if (methods == null) {
            methods = new ArrayList<String>();
            methods.add("1");
            methods.add("2");
            methods.add("3");
        }
    }

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

    @Override
    public String getItem(int position) {
        return methods.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(android.R.layout.simple_spinner_item, null);
        }
        TextView tvLabel = (TextView)convertView.findViewById(android.R.id.text1);
        tvLabel.setText("test");
        return convertView;
    }
}

更新我的Nexus 6没有问题。

1 个答案:

答案 0 :(得分:0)

I think that you should modify the code like this:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(android.R.layout.simple_spinner_item, null);
TextView tvLabel = (TextView)convertView.findViewById(android.R.id.text1);

        }else{ 
        tvLabel.setText("test");
        return convertView;}
    }

as findViewById should only be called when convertview is null. also you were missing the return convertview tag