まず第一に、私はアンドロイド開発に不慣れです。UI にスピナーを含む小さなアプリケーションを構築しています。これには、4 つの数値のセット (配列) があらかじめ定義されておりArrayAdapter
、リソース ファイルからスピナーに値を供給するために使用しています。
スピナーは正常に機能しており、ユーザーは値を選択できます。しかし、ユーザーが新しい値を入力したい場合は、新しい値を入力できるようにしたい. どうすればいいですか?
アクティビティの 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
}
}`
ありがとう、