java - android:将微调器绑定(bind)到自定义列表

标签 java android android-spinner

我试图显示一个 Spinner 列表供用户选择,然后将选择绑定(bind)到另一个 array。保存用户选择的值 surfaceCode 供以后使用。 Spinner 数组 R.array.surface_option 和要绑定(bind)的数组 R.array.surface_code 对齐并保存在 xml 中。

这是我的代码...

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"));

surfaceCode 作为错误 process stoppended 出现,可能是因为它返回 null。我的代码有什么问题?

最佳答案

surfaceCode 在最后一行代码中可以为 null,因为匿名监听器中的代码仅在进行选择时执行。

这会导致最后一行出现 NullPointerException。

即使调用 onItemSelected(),它也不会设置成员 surfaceCode,因为您已经声明了一个同名的局部变量来隐藏它。

您应该删除 surfaceCode 之前的“String”并将日志语句放在 onItemSelected() 中。

关于java - android:将微调器绑定(bind)到自定义列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10928669/

相关文章:

android - 什么属性控制 Spinner 下拉菜单背景?

java - 如何在java中实现抽象和泛型?

java - 阻塞对象属性

java - 我想停止从 Socket 中的数据输入流读取

android - 建议我从 websocket 服务器检索实时数据

android - 如何在 Android string.xml 中放置特殊的贸易字符

android - 无法从 LinkedIn 应用程序获取访问 token 。它在 onActivityResult 中返回 null

android - 使用 IntelliJ-Idea - 在微调器上获取 "Cannot Resolve Symbol"

java - 针对网站的 http client head 方法返回 503 但该网站运行正常

android - 将 Spinner 转换为字符串中的日期格式