java通过引用多个微调器的setOnItemSelectedListener传递字符串变量
好的,我已经read around看到Java只通过值传递,而不是通过引用,所以我不知道如何实现这一点
- 我在Android活动中有6个微调器,它们填充了不同的SQLite查询李>
- 填充每个微调器并设置OnItemSelectedListener的代码非常相似,因此我希望重构为一个方法,并使用每个微调器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[] { 安卓.R.id.text1 }; SimpleCursorAdapter months = new SimpleCursorAdapter(this, 安卓.R.layout.simple_spinner_item, cMonth, from, to); months.setDropDownViewResource(安卓.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
字段。字段_name(在本例中为strength)必须声明为在onItemSelectedListener中使用的最终变量,否则我将得到错误Cannot refer to a non-final variable field_name inside an inner class defined in a different method
但是,当使用每个不同的微调器时,如何让onItemSelectedListener更改不同实例成员的值?这是最重要的一行代码:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
我不能使用最后一个字符串,因为当用户选择不同的值时,变量将明显改变。我读了很多书,很难找到一个解决办法。我可以复制粘贴这段代码6次,然后忘记重构,但我真的很想知道优雅的解决方案。如果你不理解我的问题,就发表评论,我不确定我是否解释得很好
# 1 楼答案
将你的听众重构成一个新的“类”。根据需要使用正确的参数/实例进行初始化,以使重复的“代码”可重用
# 2 楼答案
您可以通过将附加类作为
fillSpinner
方法的参数传递来实现:A.创建
interface
B.稍微改变一下你的方法:
C.提供听众:
# 3 楼答案
是的,我就是这样做到的,但我仍然愿意接受新的建议,寻求一个被接受的答案,我还创造了一个悬赏
我没有像panzerschreck建议的那样创建一个新类,所以我将此作为我自己问题的新答案发布。有点像黑客,但我刚刚创建了一个if。。然后else语句来检查选择了哪个微调器,然后设置不同的实例成员
这是同学们
虽然有点黑客行为,但如果Java不允许对象真正通过引用传递,我只能这么做