2013-07-05 98 views
0

在下面的代碼,它們被實例化OnItemSelectedListener裏面直接setOnItemSelectedListener()方法,但它是一個接口下面的代碼是如何工作的精細解釋請人...OnItemSelectedListener是一個接口,但如何直接實例化?

public void addListenerOnSpinnerItemSelection() { 
     spinner1 = (Spinner) findViewById(R.id.spinner1); 
     spinner1.setOnItemSelectedListener(new OnItemSelectedListener() { 

      @Override 
      public void onItemSelected(AdapterView<?> parent, View view,int position, long id) { 
       Toast.makeText(parent.getContext(), "OnItemSelected: " +parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show(); 

      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 
       // TODO Auto-generated method stub 

      } 
     }); 
    } 
+1

外表匿名(內)類 – Blackbelt

回答

1

new OnItemSelectedListener()」將創建接口的對象,這個對象就是我們使用spinner1.setOnItemSelectedListener()

它類似於:

OnItemSelectedListener listener = new OnItemSelectedListener() { 

       @Override 
       public void onItemSelected(AdapterView<?> parent, View view,int position, long id) { 
        Toast.makeText(parent.getContext(), "OnItemSelected: " +parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show(); 

       } 

       @Override 
       public void onNothingSelected(AdapterView<?> parent) { 
        // TODO Auto-generated method stub 

       } 
      }); 

spinner1.setOnItemSelectedListener(listener); 
0

,因爲它的匿名類。

  1. 匿名類是同時聲明和初始化的。

  2. 匿名類必須擴展或實現爲一個且只有一個類或接口resp。

  3. 作爲anonymouse類沒有名稱,它只能使用一次。

例如:

button.addActionListener(new ActionListener(){ 

     public void actionPerformed(ActionEvent arg0) { 
    // TODO Auto-generated method stub 

} 
}); 
相關問題