複数のスピナーのsetOnItemSelectedListenerを参照することにより、文字列変数を渡す
-
29-10-2019 - |
質問
わかりました、私は 周りを読んでください そして、Javaは参照ではなく価値によってのみ通過することを確認するので、これを達成する方法がわかりません。
- さまざまなSQLiteクエリが入力されたAndroidアクティビティで6人のスピナーがいます。
- 各スピナーに設定してOnItemSelectedListenerを設定するコードは非常に似ているため、1つのメソッドをリファクタリングし、各スピナー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");
.
IDのスピナーを見つけます spinner1
およびのデータベースをクエリします strength
分野。この例の強度であるfield_nameは、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回コピーして貼り付けるだけで、リファクタリングを忘れることができますが、エレガントなソリューションを知りたいです。コメントを投稿してください私の質問がわからない場合は、自分自身をよく説明したかどうかはわかりません。
正しい解決策はありません