2014-10-01 79 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。