【发布时间】:2012-01-18 04:47:45
【问题描述】:
好的,我 read around 看到 Java 只通过值传递,而不是通过引用传递,所以我不知道如何实现。
- 我在一个 Android Activity 中有 6 个 Spinner,它们填充了不同的 SQLite 查询。
- 填充每个 Spinner 和设置 OnItemSelectedListener 的代码非常相似,因此我希望重构为一种方法,并使用每个 Spinner ID 和 Sqlite 查询调用 6 次。
-
如何让 Spinner onItemSelectedListener 更改每个不同 Spinner 上的正确实例成员?
public void fillSpinner(String spinner_name, final String field_name) { // This finds the Spinner ID passed into the method with spinner_name // from the Resources file. e.g. spinner1 int resID = getResources().getIdentifier(spinner_name, "id", getPackageName()); Spinner s = (Spinner) findViewById(resID); final Cursor cMonth; // This gets the data to populate the spinner, e.g. if field_name was // strength = SELECT _id, strength FROM cigars GROUP BY strength cMonth = dbHelper.fetchSpinnerFilters(field_name); startManagingCursor(cMonth); String[] from = new String[] { field_name }; int[] to = new int[] { android.R.id.text1 }; SimpleCursorAdapter months = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cMonth, from, to); months.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s.setAdapter(months); // This is setting the Spinner Item Selected Listener Callback, where // all the problems happen s.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Cursor theCursor = (Cursor) parent.getSelectedItem(); // This is the problem area. object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name)); } public void onNothingSelected(AdapterView<?> parent) { // showToast("Spinner1: unselected"); } });}
您像这样调用此方法fillSpinner("spinner1","strength");。
它找到 id 为 spinner1 的微调器,并在数据库中查询 strength 字段。 field_name,在此示例中是强度必须声明为要在 onItemSelectedListener 中使用的最终变量,否则我会收到错误 Cannot refer to a non-final variable field_name inside an inner class defined in a different method。
但是当使用每个不同的 Spinner 时,如何让 onItemSelectedListener 更改不同实例成员的值?这是最重要的代码行:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
我不能使用最终字符串,因为当用户选择不同的值时,变量显然会发生变化。我已经阅读了很多内容,并且很难找到解决方案。我可以复制并粘贴此代码 6 次而忘记重构,但我真的很想知道优雅的解决方案。如果您不理解我的问题,请发表评论,我不确定我是否解释得很好。
【问题讨论】:
-
其实,在onItemSelected 中你想要什么以及你面临什么问题并不清楚。请详细说明。
-
Cannot refer to a non-final variable field_name inside an inner class defined in a different method.,为什么不在主类中全局声明field_name。
标签: java android pass-by-reference android-spinner