首先,我是android开发的新手。我正在构建一个小型应用程序,它的 UI 中包含一个微调器,它具有四个数字的预定义集合(数组),我正在使用ArrayAdapter
从资源文件将值提供给微调器。
微调器工作正常,用户可以选择值。但我也希望用户能够输入新值,如果他们想输入一个新值。我该怎么做?
Activity 的 onCreate 方法中的代码:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.points_preset, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new SpinnerActivity());
SpinnerActivity 类的代码:
更新包括输入对话框:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, final View view,
int pos, long id) {
if (pos==3)
{
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
new AlertDialog.Builder(MainActivity.this)
.setMessage("Enter your Point here")
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable editable = input.getText();
//if I uncomment following line, the application terminates
// Spinner spinner = (Spinner) findViewById(R.id.spinner);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
`
Strings.xml 资源文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">PointCalculator</string>
<string name="menu_settings">Settings</string>
<string-array name="points_preset">
<item>3</item>
<item>10</item>
<item>0</item>
<item>Oth</item>
</string-array>
</resources>
SpinnerActivity 类的更新和工作版本
`
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, final View view,
int pos, long id) {
if (pos==3)
{
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
new AlertDialog.Builder(MainActivity.this)
.setMessage("Enter your Point here")
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable editable = input.getText();
arrayList.add(editable.toString());
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}`
谢谢,