2011-09-13 28 views
1

我在我的android應用程序中有一個微調控件,我希望用戶從微調框中選擇一個選項。一旦選擇該選項,用戶可以被重定向到另一個意圖。我的問題是如何從spinner的onitemselcted方法調用意圖?我該如何從spinners調用意圖onitemSelected方法

或者我正在絞擰還有其他方法可以做到這一點。我需要用戶先從下拉菜單中設置選項,然後才能繼續下一頁。

如果我把startactivity(意向),在我的onitemselected方法我得到這個 錯誤的方法startActivity(意向)是未定義的 型MyOnItemSelectedListener(Myonitemselectedlistner是我的類 器具OnItemSelectedListener)

這是我onitemslectedlistner代碼

class MyOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 

     Context ctx = view.getContext(); 

     SharedPreferences myPrefs = ctx.getSharedPreferences("hello", android.content.Context.MODE_WORLD_READABLE); 

     SharedPreferences.Editor prefsEditor = myPrefs.edit();  
     prefsEditor.putString("city", parent.getItemAtPosition(pos).toString());  
     prefsEditor.commit(); 
      Intent intent = new Intent(); 
     intent.setClass(ctx, MainActivity.class); 
     startActivity(intent); 


    } 

    public void onNothingSelected(AdapterView parent) { 

     //do nithong 
    } 
} 
+0

ü可以發佈您的Spinner OnItemSelcted方法的代碼。 – Venky

+0

添加請參閱 –

+0

而不是Intent intent = new Intent(); intent.setClass(ctx,MainActivity.class); startActivity(intent); 更改爲startActivity(新的意圖(Classnmae.this,Main.class)) – Venky

回答

4

嘗試做這樣的事情:

YourParentClassName.this.startActivity(intent); 

下面是經過全面測試的實現......這工作:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 
     public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { 
      if (position == 1){ 
       Intent intent = new Intent(MyActivity.this, AnotherActivity.class); 
       MyActivity.this.startActivity(intent); 
      } 
     } 

     public void onNothingSelected(AdapterView<?> parentView) { 
      // To do ... 
     } 

    }); 
+0

沒有這個工作不起作用 –

+0

我剛剛更新了我的答案,並使用了完整的測試解決方案。不要讓你的活動實現OnItemSelectedListener。你不需要。顯然,調整類的名稱以匹配你的。如果這不適合你,你做錯了什麼。 – SBerg413

+0

感謝它的工作 –

0

你onitemselected方法是一個私有的類T內帽子實現了OnItemSelectedListener,它沒有定義startActivity。 startActivity方法是Activity的一部分。

您應該在父活動中創建一個方法,然後從那裏調用startActivity。您可以從您的私人課程打電話給您的家長活動。

+0

如果我這樣做,它問我讓該方法靜態,如果我使方法定義爲活動的一部分靜態我可以調用啓動活動它說不能對非靜態方法做一個靜態引用 –

0

讓你的活動實現了這個接口

public class MyApp implements OnItemSelectedListener{ 

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 

     Context ctx = view.getContext(); 

     SharedPreferences myPrefs = ctx.getSharedPreferences("hello", android.content.Context.MODE_WORLD_READABLE); 

     SharedPreferences.Editor prefsEditor = myPrefs.edit();  
     prefsEditor.putString("city", parent.getItemAtPosition(pos).toString());  
     prefsEditor.commit(); 
      Intent intent = new Intent(); 
     intent.setClass(ctx, MainActivity.class); 
     MyApp.this.startActivity(intent); 


    } 

    public void onNothingSelected(AdapterView parent) { 

     //do nithong 
    } 



} 
相關問題