2012-11-27 38 views
0

這是實現AdapterView.OnItemSelectedListener的嵌套類。這提供了一種回調方法,可以在從Spinner中選擇一個項目時通知我的應用程序。但我不知道如何將選定的字符串值傳遞給主要活動?android在主要活動中獲取選定的字符串

public class CustomOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) { 
    String selected = parent.getItemAtPosition(pos).toString(); 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) { 
     // Do nothing. 
    } 

} 

我在主要活動中調用了象

 public void addListenerOnSpinnerItemSelection() { 
    spinner1 = (Spinner) findViewById(R.id.spinner1); 
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener()); 
    // I need the selected value here......... 
    } 

回答

0

如果你的聽衆是嵌套子類相關的活動,你應該能夠簡單地調用直接從活動的方法?

public void doSomething(String selected) { 
    // do something here... 
} 

public class YourItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
     String selected = parent.getItemAtPosition(pos).toString(); 
     doSomething(selected); // <=== THIS 
    } 

    public void onNothingSelected(AdapterView parent) { 
     // Do nothing. 
    } 
} 
+0

我更新了帖子,請查看,這個解釋我想要的 –

+0

請問您能幫我做到嗎? –

+0

在您指定的位置,無法訪問該值 - 尚不可用。在那個地方,你只是綁定一個事件監聽器。該值將在事件偵聽器中可用,然後將其傳回給父活動中的相關代碼是您的責任 - 您可以通過調用方法來完成此操作。或者,也許你在你的CustomOnItemSelectedListener類中添加了一個getter屬性。 –

0

在您的自定義SpinnerAdapter可以設置在查看

myFirstView.setTag("First"); 

字符串作爲標籤,在onItemSelected回調你可以從查看標籤。

String selectedContent = (String)view.getTag(); 
+0

我更新了帖子,請檢查出來,這說明了我想要的! –

+0

你能幫我做到嗎? –

相關問題