I think I am making a design error in my Android app somewhere. My (simplified) code is pasted below.
I am using the writeMidi method in MainActivity. However, I would also like to use it, or actually just trigger it, when “onItemSelected” is triggered in the custom listener.
I am a bit torn on how to do that. Should I redesign this code to fit the customlistener in the main activity?
Thanks for any help.
public class MainActivity extends Activity{
int song = 0;
int[] music;
public int instrument;
public CustomOnItemSelectedListener listener;
// *******************************************************
// set Layout - on create
// *******************************************************
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instrument = 0;
listener = new CustomOnItemSelectedListener();
addListenerOnSpinnerItemSelection();
//more stuff, including using the writeMidi method
};
public void addListenerOnSpinnerItemSelection(){
instrumentSp = (Spinner) findViewById(R.id.instrument);
instrumentSp.setOnItemSelectedListener(listener);
}
public void writeMidi(int[] music, int count) {
// so some stff
}
}
and in a separate file;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private int instrument = 0;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"Please wait a minute for the instrument to be changed. ", Toast.LENGTH_SHORT).show();
instrument = pos;
}
public int getInstrument(){
return instrument;
}
}
I tried a number of the solutions suggested, but could get none of them to fully work.
So I solved it by not using a separate class like this: