[Android] Spinner 判斷是由人為還是程式選擇item的

 單刀直入的說


    一般在程式裡寫以下程式:

        spinner.setSelection(0);

    程式自然會跳回onItemSelected裡選擇第0個值並顯示在ui上,代表是程式下命令選擇的。


   如果要在程式裡判斷是人為對spinner進行選擇的還是程式下命令選擇的:


    可以執行如下程式碼:

private Boolean isUserAction = false;


public void onItemSelected( ... ) {

if( isUserAction ) {
// code for user initiated selection
} else {
// code for programmatic selection
// also triggers on init (hence the default false)
}

// reset variable, so that it will always be true unless tampered with
isUserAction = true;
}

public void myButtonClick( ... ) {
isUserAction = false;
mySpinner.setSelectedItem ( ... );
}


isUserAction true就是代表人為操作的,false程式操作


參考:

    https://stackoverflow.com/questions/2833121/spinnerhow-to-know-whether-item-selection-was-changed-programmatically-or-by-a


留言

熱門文章