无法动态设置setVisibility()参数

时间:2014-10-01 10:18:42

标签: java android view

我正在尝试按如下方式设置按钮的可见性:

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传递给它。可以在这做什么?

2 个答案:

答案 0 :(得分:18)

当您知道自己在做什么时,可以使用

在本地取消此Android Studio检查
//noinspection ResourceType

例如,

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

答案 1 :(得分: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。