smo*_*ose 2 java android android-spinner android-textinputlayout material-components-android
我正在使用 Material 在 android studio 中使用 Java 设计一个带有下拉列表的表单。
我想将用户从下拉列表中所做的选择保存到一个字符串中,这样我就可以将其保存到 Firebase,但是当我尝试记录结果时,它说选择为空。
有谁知道我如何捕获用户从这种类型的下拉菜单中选择的内容?我以前确实有一个可以工作的 Spinner,但这似乎并没有以相同的方式工作。
我的XML代码如下
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/cpdTypeLayout"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:hint="Activity Type">
<AutoCompleteTextView
android:id="@+id/cpdType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none" />
</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)
我的 AddAdactivity.java 代码是
//CPD TYPE DROPDOWN MENU
cpdTypeLayout = findViewById(R.id.cpdTypeLayout);
cpdType = findViewById(R.id.cpdType);
String[] type = new String[]{
"Formal Education Completed", "Other Completed", "Professional Activities", "Self-Directed Learning", "Work-Based Learning"
};
ArrayAdapter<String> adapterType = new ArrayAdapter<>(
AddActivity.this,
R.layout.dropdown_item,
type
);
cpdType.setAdapter(adapterType);
cpdType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedTypeResult = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Log.d("TAG", "You have selected " + selectedTypeResult);
Run Code Online (Sandbox Code Playgroud)
编辑:此后尝试过这个,但没有运气。
((AutoCompleteTextView)cpdTypeLayout.getEditText()).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapterType.getItem(position);
String typeItem = ((AutoCompleteTextView)cpdTypeLayout.getEditText()).getText().toString();
Log.d("TAG", "selected type is:" + typeItem);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Run Code Online (Sandbox Code Playgroud)
要获得String您可以使用:
String selectedValue =((AutoCompleteTextView)textInputLayout.getEditText()).getText();
Run Code Online (Sandbox Code Playgroud)
否则,如果您想使用侦听器,则可以使用以下内容:
((AutoCompleteTextView)textInputLayout.getEditText()).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String selectedValue = arrayAdapter.getItem(position);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1459 次 |
| 最近记录: |