好的,我有 read around 并且看到 Java 仅通过值传递,而不是通过引用传递,所以我不知道如何实现这一点。
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 次而忘记重构,但我真的很想知道优雅的解决方案。如果您不明白我的问题,请发表评论,我不确定我是否解释得很好。
最佳答案
您可以通过将附加类作为 fillSpinner
方法的参数传递来实现:
A. 创建 interface
public interface OnSpinnerValueSelected {
void onValueSelected(String selectedValue);
}
B. 稍微改变一下你的方法:
public void fillSpinner(String spinner_name, final String field_name,
final OnSpinnerValueSelected valueChangeListener) {
// Prepare spinner
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
valueChangeListener.onValueSelected(theCursor
.getString(theCursor.getColumnIndex(field_name)));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
C. 提供监听器:
fillSpinner("spinner1","strength", new OnSpinnerValueSelected() {
public void onValueSelected(String selectedValue) {
yourObject.setField(selectedValue);
}
});