[英]How to fix automatic view another activity on spinner onItemSelected methods
我正在研究需要android studio中微調小部件的簡單android項目。 我想做的是,當用戶從微調器中選擇選項時,它將打開另一個活動。 而我在編碼中間。 我決定在Intent中使用switch case條件。 問題是,每當我運行該應用程序時,它將自動轉到我聲明的特定活動位置。 即使我在微調器上沒有選擇任何選擇。 注意:log cat不顯示任何錯誤
像我這樣的初學者非常感謝您的幫助。
public class CustomOnItemSelectedListener extends Activity implements
OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// **************************** below here is where I start the new activity
switch (pos) {
case 0 :
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1 :
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2 :
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
// **************************** above here is where I start the new activity
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
嘗試這個
在類中聲明一個int,例如在onCreate()
之前,然后在onCreate()
中將其分配為0。在使用微調器選擇某些內容時,使用此變量檢查其是否大於0,如下例所示。
public class ExampleActivity extends AppCompatActivity {
private int spinnerCheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinnerCheck = 0;
mMySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int itemId = (int) id;
// For some reason this method is called during initialization, so increment counter once to prevent it from auto selecting first item when loading view
spinnerCheck += 1;
if (spinnerCheck > 1) {
switch (pos) {
case 0:
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1:
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2:
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
由於某種原因,它選擇創建后的第一個項目,不確定為什么,但這應該可行。
默認情況下,創建應用程序時,將在微調器中選擇第一個選項,然后調用偵聽器。 為了避免這種情況,您可以使用@Simon的解決方案
或者您可以使用按鈕來確認選擇,並在按下此按鈕時而不是在微調器中選擇某個項目時更改您的活動。
更新您還可以使用無用的文本填充微調器的第一個條目,該文本可以是諸如“選擇活動”之類的標題,然后在偵聽器中將開關切換為1而不是0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.