私が抱えている問題は、spinner2
(たとえば) カナダを選択した後に入力したいのですが、何らかの理由で、spinner2
カナダを選択した後ではなく、起動時に入力されることです。また、文字列配列を接続してspinner2
、何も起動しないことを確認しましたが、それでも機能しません。これが私がこれまでに持っているものです:
public class MainActivity extends Activity {
private Spinner spinner1, spinner2;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.countries,
android.R.layout.simple_list_item_1);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
TextView tv = (TextView)v; // cast the View to a TextView
if ("Canada".equals(tv.getText().toString()));
{
addItemsOnSpinner2();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
list.add("hello");
list.add("holla");
list.add("hey");
list.add("hi");
ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(new Spinner2());
spinner2.setOnItemSelectedListener(new Spinner2());
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Result : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()), Toast.LENGTH_SHORT).show();
}
});
}
}
Spinner2.java*
public class Spinner2 implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView parent) {
}
}