我正在尝试根据微调器选择在imageview中更改图像,在stackoverflow和internet上查找类似的东西,但没有任何效果!为什么?任何帮助赞赏!这是我的.java来源:
公共类ChordsActivity扩展Activity实现OnItemSelectedListener { 旋转器旋转器;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chords);
spinner = (Spinner) findViewById(R.id.SpinnerAkordi);
spinner.setOnItemSelectedListener(this);
ImageView chord_img=(ImageView) findViewById(R.id.image);
chord_img.setImageResource(R.drawable.c_dur);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int position = spinner.getSelectedItemPosition ();
ImageView chord_img= new ImageView(this); //delete this and it will work
switch (position){
case 0:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("C").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.c_dur);
break;
case 1:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("D").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.e_dur);
break;
case 2:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("E").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.e_dur);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
.xml的imageview部分:
答案: 删除:ImageView chord_img = new ImageView(this); 因为我已经有了一个imageview,我用这条线创建了一个看不见的新imageview。
答案 0 :(得分:2)
如果将局部变量chord_img
提升为字段,则可能有所帮助。即:
private ImageView chord_img;
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int position = spinner.getSelectedItemPosition ();
chord_img = new ImageView(this);
switch (position){
case 0:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("C").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.c_dur);
break;
case 1:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("D").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.e_dur);
break;
case 2:
new AlertDialog.Builder(this).setTitle("Odabrali ste akord:").setMessage("E").setNeutralButton("Close", null).show();
chord_img.setImageResource(R.drawable.e_dur);
break;
}
}