问题
在一个 Android 项目中,我在公共类中有一些私有变量,警告消息不断提醒我实现 getter 和 setter,而不是直接将值分配给这些私有变量。
问题
什么时候应该为私有变量实现 getter/setter?
源代码
MainActivity.java
public class MainActivity extends Activity implements OnTouchListener {
// There are a few private variables that I used in the following methods in this class MainActivity
private boolean _isMenuHidden = true;
private boolean _isMenuMoveTriggered = false;
private int _xDelta = 0;
private int _yDelta = 0;
private int _xTouchDown = 0;
private int _yTouchDown = 0;
private int _xPrevious = 0;
private int _yPrevious = 0;
// Some code omitted....
// Implements View.OnTouchListener
@Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
view = (View) view.getParent();
LinearLayout.LayoutParams mLayoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
_xTouchDown = X;
_yTouchDown = Y;
_xPrevious = X;
_yPrevious = Y;
_xDelta = X - mLayoutParams.leftMargin;
return false;
// case MotionEvent.ACTION_DOWN:
//break;
case MotionEvent.ACTION_MOVE:
if (((X - _xDelta) < -384) || ((X - _xDelta) > 0)) {
// The move allows at most 480 * 80% = 384 pixels leftward and
// zero pixels rightward
} else {
// Some code omitted....
}
break;
// Some code omitted....
} // switch ()
} // End of public boolean onTouch()
// Some code omitted....
} // End of public class MainActivity