好吧,我read around并且看到Java只通过值传递,而不是通过引用,所以我不知道如何实现这一点。通过引用多个Spinner的setOnItemSelectedListener传递字符串变量
- 我有6个Spinners在Android Activity中被填充了不同的SQLite查询。
- 填充每个Spinner并设置OnItemSelectedListener的代码非常相似,所以我希望重构为一个方法,并使用每个Spinner ID和Sqlite查询调用它6次。
如何获得微调onItemSelectedListener更改每个不同微调器上的正确实例成员?
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");
。
它找到编号为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更改不同实例成员的值?这是所有重要的代码行:
我不能使用最终的字符串,因为当用户选择不同的值时,变量显然会改变。我已经读了很多,很难找到解决方案。我可以复制并粘贴这段代码6次,忘掉重构,但我真的很想知道这个优雅的解决方案。如果你不明白我的问题,请发表评论,我不确定我是否能够很好地解释自己。
实际上,目前尚不清楚你想要什么,什么问题你都面临着onItemSelected。请详细说明。 – jeet 2012-01-18 04:59:30
'不能在不同的方法中定义的内部类中引用非最终变量field_name',为什么不在主类中全局声明'field_name'。 – 2012-01-21 04:35:24