2014-10-01 32 views
10

我想設置的可視性按鈕如下:不能夠動態地設置setVisibility()參數

public Bundle setActivityState(Bundle bundle){ 
    startBtn = (Button) findViewById(R.id.startSensorsBtn); 

    startBtn.setVisibility(
      getVisibilityState(bundle, PersistanceConstants.START_BTN_STATE) 
    );   

    return bundle; 
} 

public int getVisibilityState(Bundle bundle, String keyName){ 
    if (bundle.getInt(keyName) == View.VISIBLE){ 
     return View.VISIBLE; 
    } else if (bundle.getInt(keyName) == View.INVISIBLE){ 
     return View.INVISIBLE; 
    } else if (bundle.getInt(keyName) == View.GONE){ 
     return View.GONE; 
    } 

    return 0; 
} 

但我得到的錯誤:

Must be one of: View.VISIBLE, View.INVISIBLE, View.GONE less... (Ctrl+F1) 
Reports two types of problems: 
- Supplying the wrong type of resource identifier. For example, when calling Resources.getString(int id), you should be passing R.string.something, not R.drawable.something. 
- Passing the wrong constant to a method which expects one of a specific set of constants. For example, when calling View#setLayoutDirection, the parameter must be android.view.View.LAYOUT_DIRECTION_LTR or android.view.View.LAYOUT_DIRECTION_RTL. 

同時呼籲

getVisibilityState(bundle, PersistanceConstants.START_BTN_STATE) 

我不知道如何解決這個問題。我知道它期待着一組給定的值,但我所知道的是通過一個int它。這裏可以做些什麼?

+0

發佈您的錯誤日誌.. – Sats 2014-10-01 10:22:35

+0

getVisibilityState達到'返回0;'行?請發佈您的錯誤日誌。 – wendigo 2014-10-01 10:24:43

+0

對不起,我沒有提到這一點。我在Android Studio編譯期間得到了這個。 – jsbisht 2014-10-01 10:27:22

回答

18

當你知道你在做什麼,你可以在本地使用

//noinspection ResourceType 

例如抑制這種Android Studio中檢查,

//noinspection ResourceType 
startBtn.setVisibility(bundle.getInt(PersistanceConstants.START_BTN_STATE)); 
+1

哇。這工作。非常感謝laalto。 – jsbisht 2014-10-01 10:37:39

17

有點遲到了,但如果你另一種解決方案在你的代碼中使用了很多,你有一個返回int的方法來定義你自己的Visibility註釋,所以像這樣:

public class MyStuff { 

    @IntDef({View.VISIBLE, View.INVISIBLE, View.GONE}) 
    @Retention(RetentionPolicy.SOURCE) 
    public @interface Visibility { 
    } 

    public @Visibility int getVisibility() { 
     return View.GONE; 
    } 
} 

如果你這樣做,那麼AS不會再抱怨了,因爲你正在返回一個合適的int def。