![](/img/trans.png)
[英]Android EditText's text value to set the selected item in the Spinner
[英]Reaching the selected item's value on spinner
我正在開發一個注冊系統。 我需要通過獲取用戶輸入來創建院系,然后將學生分配給這些院系。 選擇學生姓名時,我應該顯示教師信息。 我正在使用 arraylist 來保持教師的輸入。 此外,我正在使用 select 教員的微調器。 But somehow I can't reach the faculty name when a spinner item selected.It says null everytime. 這是我的代碼的一部分。
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
ArrayList<String> facultyArr = new ArrayList<String>();
.
.
.
protected void onCreate(Bundle savedInstanceState) {
spnF.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
ArrayAdapter<String> af = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, facultyArr);
af.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnF.setAdapter(af);
spnF.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
pos = parent.getSelectedItemPosition();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String facOfStu = facultyArr.get(pos);
.
.
.
.}//end of onCreate
如何從最初的 null arrayList 中獲得選定的教師? 感謝大家閱讀。
您需要采取被動的方法。
spnF.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//You can get the faculty when the user selects it.
String faculty = facultyArr.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
當您知道至少存在一個時,您還可以獲得特定的教師。
//Simulate filling the faculty list.
facultyArr.add("This guy");
facultyArr.add("That guy");
facultyArr.add("The guy");
//Notify the adapter it needs to relook at its data.
af.notifyDataSetChanged();
String faculty = facultyArr.get(0);
調用String facOfStu = facultyArr.get(pos);
如果facultyArr
空,在 onCreate 結束時將導致IndexOutOfBoundsException
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.