2017-06-04 34 views
0

我希望能夠在從微調框中選擇項目時填充圖像視圖!我試圖實現onitemselectedlistener,但無法讓代碼正常工作,所以尋求幫助!使用spinner選擇的項目填充圖像查看

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; 
} 

}

+0

你引用'R.id.mainimage'兩次 – Pzy64

+0

是的,我注意到我在onClick方法中引用它! –

+0

但是,你刪除了它嗎? 。onClick已經給你'視圖'這是你的圖像視圖本身.. ..刪除第二個聲明,並使用'view.startAnimation(a);'而不是 – Pzy64

回答

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) { 

     } 
    }); 
+0

可繪製的colot ok,但列表中有5個項目可供選擇,並且需要根據所選項目返回其中的一個!也ItemData是拋出一個錯誤,不兼容的類型 –

+0

你可以分享你的itemData類也 – Pzy64

+0

剛剛添加itemdata類 –