What kind of variable to declare in this "draggable popup" code?

50 views Asked by At

I am inserting the following lines (from pskink post 3-2-14) into my popup Android activity file. This is being placed in the onCreate() in an already working project. Android Studio wants me to declare the following 3 as either local variable, a parameter or a field. The 3 are: mPopup, mCurrentX and mCurrentY. If I just do the trial-and-error method, trying one at a time, that might work, eh? Or any ideas about how to tell which to use?

  1. If I select 'local', AS changes mPopup to 'PopupWindow'.
  2. If I select 'parameter, AS asks about refactoring.

Here is the code:

final View cv = new View(this);
setContentView(cv);

TextView tv = new TextView(this);
tv.setBackgroundColor(0xffeeeeee);
tv.setTextColor(0xff000000);
tv.setTextSize(24);
tv.setText("click me\nthen drag me");
tv.setPadding(8, 8, 8, 8);
mPopup = new PopupWindow(tv, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
OnTouchListener otl = new OnTouchListener() {
    private float mDx;
    private float mDy;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            mDx = mCurrentX - event.getRawX();
            mDy = mCurrentY - event.getRawY();
        } else
        if (action == MotionEvent.ACTION_MOVE) {
            mCurrentX = (int) (event.getRawX() + mDx);
            mCurrentY = (int) (event.getRawY() + mDy);
            mPopup.update(mCurrentX, mCurrentY, -1, -1);
        }
        return true;
    }
};
tv.setOnTouchListener(otl);

mCurrentX = 20;
mCurrentY = 50;
cv.post(new Runnable() {
    @Override
    public void run() {
        mPopup.showAtLocation(cv, Gravity.NO_GRAVITY, mCurrentX, mCurrentY);
    }
});
1

There are 1 answers

0
David Wasser On

By convention, variables beginning with "m" are member variables (class fields), not local variables. In this case that looks correct because they need to have a lifetime outside of these methods.