【问题标题】:Not able to dynamically set the setVisibility() parameter无法动态设置 setVisibility() 参数
【发布时间】:2014-11-26 03:51:34
【问题描述】:

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

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

【问题讨论】:

  • 发布您的错误日志..
  • getVisibilityState 到达线return 0;?请发布您的错误日志。
  • 对不起,我没有提到这个。我在 Android Studio 的编译期间得到了这个。
  • return 0 更改为return View.VISIBLE
  • 我做到了。它仍然给出同样的错误。

标签: java android view


【解决方案1】:

聚会有点晚了,但是如果您在代码中大量使用它并且您有一个返回该 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。

【讨论】:

    【解决方案2】:

    当你知道你在做什么时,你可以在本地禁止这个 Android Studio 检查

    //noinspection ResourceType
    

    例如,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多