我想我在某个地方的 Android 应用程序中犯了一个设计错误。我的(简化的)代码粘贴在下面。
我在 MainActivity 中使用 writeMidi 方法。但是,当在自定义侦听器中触发“onItemSelected”时,我也想使用它,或者实际上只是触发它。
我对如何做到这一点感到有些不知所措。我应该重新设计此代码以适应主要活动中的自定义侦听器吗?
谢谢你的帮助。
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
}
}
并在一个单独的文件中;
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;
}
}