使用从微调器中选择的项填充imageview

时间:2017-06-04 15:27:22

标签: java android android-imageview android-spinner

我希望能够在从微调器中选择一个项目时填充imageview!我试图实现onitemselectedlistener但无法使代码正常工作,以寻求帮助!

public class MainActivity extends AppCompatActivity {


Context context = this;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<ItemData> list = new ArrayList<>();
    list.add(new ItemData("Blue", R.drawable.blue));
    list.add(new ItemData("Green", R.drawable.green));
    list.add(new ItemData("Orange", R.drawable.orange));
    list.add(new ItemData("Pink", R.drawable.pink));
    list.add(new ItemData("Yellow", R.drawable.yel));

    Spinner sp = (Spinner) findViewById(R.id.spinner);
    SpinnerAdapter adapter = new SpinnerAdapter(this,
            R.layout.spinner_layout, R.id.txt, list);
    sp.setAdapter(adapter);

    mp = MediaPlayer.create(context, R.raw.sound);


    ImageView myView = (ImageView) findViewById(R.id.mainimage);


    myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    mp = MediaPlayer.create(context, R.raw.sound);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

            ImageView myView = (ImageView) findViewById(R.id.mainimage);
            Animation a = new RotateAnimation(0.0f, 360.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                    0.5f);
            a.setInterpolator(new LinearInterpolator());
            a.setRepeatCount(-1);
            a.setDuration(500);
            a.setFillAfter(true);
            a.setRepeatCount(7);
            myView.startAnimation(a);

        }
    });
}

}

public class ItemData {

String text;
Integer imageId;
public ItemData(String text, Integer imageId){
    this.text=text;
    this.imageId=imageId;
}

public String getText(){
    return text;
}

public Integer getImageId(){
    return imageId;
}

}

1 个答案:

答案 0 :(得分:1)

如果您想在单击某个项目时显示颜色..

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ItemData data = sp.getSelectedItem();
            int res = data.getImageId();  //change Integer type to int  if error exists
            myView.setImageDrawable(getResources().getDrawable(res));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });