2014-04-28 23 views
1

的項目,我實現自定義的微調:獲取定製微調

public class MyAdapter extends ArrayAdapter<String> 
     { 

       public MyAdapter(Context context, int textViewResourceId, 
          String[] objects) { 
         super(context, textViewResourceId, objects); 
         // TODO Auto-generated constructor stub 
       } 
       @Override 
      public View getDropDownView(int position, View convertView,ViewGroup parent) { 
       return getCustomView(position, convertView, parent); 
      } 

      @Override 
      public View getView(int position, View convertView, ViewGroup parent) { 
       return getCustomView(position, convertView, parent); 
      } 

      public View getCustomView(int position, View convertView, ViewGroup parent) { 

       LayoutInflater inflater=getLayoutInflater(); 
       View row= inflater.inflate(R.layout.spinner, parent, false); 
       TextView label=(TextView)row.findViewById(R.id.textView1); 
       label.setText(data1[position]); 

       ImageView icon=(ImageView)row.findViewById(R.id.imageView1); 
       icon.setImageResource(images[position]); 

       return row; 
       } 

     } 

,並設置爲這樣的微調:

spinner_choose_network_spinner.setAdapter(new MyAdapter(this, R.layout.spinner, data1)); 

我的問題是如何獲得當前選定項的TextView的價值我的微調?

回答

3
Object selection = sp.getSelectedItem(); 

這將返回您可以查詢從

的信息在適配器需要實現getItem(int position)

,並返回所需的項目所選擇的項目,選擇將getItem(selectedPosition)

假設你的getItem是

public String getItem(int position){ 
return data1[position]; 

} 

然後String selected = spinner.getSelectedItem();

將返回data1[selectedPosition]

爲了簡單起見,我建議你創建一個新的對象

public class MyCustomObject{ 

    String title; 
    int imageResource; 

} 

和你的數據數組,然後將

ArrayList<MyCustomObject>data = new ArrayList<MyCustomObject>(); 

填充此陣莫名其妙

,現在你的行會

 public View getCustomView(int position, View convertView, ViewGroup parent) { 

      LayoutInflater inflater=getLayoutInflater(); 
      View row= inflater.inflate(R.layout.spinner, parent, false); 
      TextView label=(TextView)row.findViewById(R.id.textView1); 
      label.setText(data.get(position).title); 

      ImageView icon=(ImageView)row.findViewById(R.id.imageView1); 
      icon.setImageResource(data.get(position).imageResource); 

      return row; 
      } 

,然後你的getItem將

public MyCustomObject getItem(int position){ 

return data.get(position); 
} 

,然後你的選擇將是

MyCustomObject selection = spinner.getSelectedItem(); 

,你可以看到selection.title將可用,以及作爲selection.imageResource如果您需要它