简体   繁体   English

android:将微调框绑定到自定义列表

[英]android: bind spinner to a custom list

I am trying to display a Spinner list for user to select, then take the selection to bind to another array . 我试图显示一个Spinner列表供用户选择,然后将选择绑定到另一个array The user-selected value surfaceCode is saved for later use. 用户选择的值surfaceCode将保存以备后用。 The Spinner array R.array.surface_option and the array to bind R.array.surface_code are aligned and saved in xml. Spinner数组R.array.surface_option和绑定R.array.surface_code的数组对齐并保存在xml中。

This is my code... 这是我的代码...

spinnerSurface = (Spinner) findViewById(R.id.spinnerSurface);
ArrayAdapter<CharSequence> adapterSurface = ArrayAdapter.createFromResource(this, R.array.surface_option, android.R.layout.simple_spinner_item);
adapterSurface.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSurface.setAdapter(adapterSurface);

spinnerSurface.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { 
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { 
        TextView tx = (TextView)v; 
        Log.i("\n\nid",String.valueOf(tx.getText()));
        String surfaceCode = getResources().getStringArray(R.array.surface_code)[spinnerSurface.getSelectedItemPosition()];
    }

    public void onNothingSelected(AdapterView<?> arg0) {
    } 
});

Log.d("code outside", surfaceCode.trim() + " is equal to SW: " + surfaceCode.trim().equals("SW"));

The surfaceCode comes out as error process stopped unexpectedly , probably because it returns null . 当错误process stopped unexpectedlysurfaceCode出现了,可能是因为它返回了null What's wrong with my code? 我的代码有什么问题?

surfaceCode can be null in the last code line because the code in the anonymous listener is only executed when the selection is made. 在最后一行代码中,surfaceCode可以为null,因为仅在进行选择时才执行匿名侦听器中的代码。

This would cause a NullPointerException in the last line. 这将在最后一行中引发NullPointerException。

Even if onItemSelected() is called, it will not set the member surfaceCode because you have declared a local variable of the same name that is shadowing it. 即使onItemSelected()被调用,它也不会设置成员surfaceCode,因为您已经声明了与它相同名称的局部变量。

You should remove the "String " before the surfaceCode and put the log statement inside onItemSelected(). 您应该在surfaceCode之前删除“ String”,并将log语句放在onItemSelected()中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM