设置可变数量的微调器的itemListener

时间:2012-06-08 17:27:25

标签: android android-layout android-spinner

    int numberofSpinner = TransportResult.Transfers.size();
    Spinner spin=null;
    for(int i=0;i<numberofSpinner;i++)
    {
        spin = new Spinner(this);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,1);
        spinLayout.addView(spin,p);
        spin.setId(i);
        Transfer transfer = TransportResult.Transfers.get(i);
        ArrayList<CharSequence> s = new ArrayList<CharSequence>();
        for( Line l : transfer.TransferLine)
        {
            s.add(l.ShortName+" - "+Helper.FindTransportTypeText(l.LineType));
        }
        adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item,s);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spin.setAdapter(adapter);
    }
    spin.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                  int position, long id) {
           if(parent.getId()==0){
       System.out.println("spin 1 is called");
               String str = (String)parent.getSelectedItem(); 
         }else if(parent.getId()==1){
       System.out.println("spin 2 is called");
               String str = (String)parent.getSelectedItem();  
     }
         }   
      public void onNothingSelected(AdapterView<?> arg0) {

          }
      });

如果微调器的数量大于1,则仅触发最后一个微调器。例如;我在屏幕上有3个微调器,当我选择第一个或第二个微调器的项目时,听众永远不会被触发。只有第三个微调器才会触发侦听器。我怎么解决这个问题?

谢谢

1 个答案:

答案 0 :(得分:1)

<强>更新

当你使用多个微调器时,然后对每个微调器spin.setId(int)进行setid。你可以检查OnItemSelected method.中的id。请注意,当你第一次设置onitemSelected onItemSelected时会被调用。

 spin.setOnItemSelectedListener(new OnItemSelectedListener() {
              @Override
               public void onItemSelected(AdapterView<?> parent, View view,
                        int position, long id) {

                 if(parent.getId()==1){
             System.out.println("spin 1 is called");
                     String str = (String)parent.getSelectedItem(); 
               }else if(parent.getId()==2){
             System.out.println("spin 2 is called");
                     String str = (String)parent.getSelectedItem();  
           }
               }   
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

                }
            });