非常基本的变量超出范围问题 - Java Android

时间:2015-01-07 18:42:29

标签: java android instance scope

我正在尝试使用以下3个变量:

public boolean mDetailsExpanded;

public int mHeightBefore;

public String mHeaderItem;

然而,当我将它们分配给字符串时,boolean和int:

 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
            int heightBefore) {
        mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
        String mHeaderItem = i.toString();
        boolean  mDetailsExpanded = expanded;
        int mHeightBefore = heightBefore;             

    }

然后尝试保存它们:

  @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
        outState.putBoolean(getTag(), mDetailsExpanded);
        outState.putInt(getTag(),  mHeightBefore);
        outState.putString(getTag(), mHeaderItem);
        super.onSaveInstanceState(outState);

    }

由于超出范围,它们不断返回null。我如何纠正这一点,使它们在onSaveInstanceState的范围内,从而保持它们的值?

2 个答案:

答案 0 :(得分:4)

setMessageDetailsExpanded中,您需要创建局部变量,而不是分配给您的成员变量。将其更改为:

public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
            int heightBefore) {
        mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
        mHeaderItem = i.toString();
        mDetailsExpanded = expanded;
        mHeightBefore = heightBefore;             

}

答案 1 :(得分:0)

String mHeaderItem = i.toString();
boolean  mDetailsExpanded = expanded;
int mHeightBefore = heightBefore;             

这是局部变量,其范围是方法范围。这就是为什么不能在方法之外访问的原因。