ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Android] Context 를 매개인자로 갖는 메소드, this는 왜 쓰는걸까?
    BACK-END/Android 2020. 11. 10. 16:07

     

    developer.android.com/reference/android/app/Activity

     

     

     

    Context 의 가족관계도를 살펴보자.

    Object

    | Context

      | ContextWrapper

          | ContextThemeWrapper

            | Activity

                | MainActivity

                  | class MainActivity extends Activity

     

     

    이 가족 관계도를 설명해보자면,

    ContextWrapper 는 Context 다.

    ContextThemeWrapper 도 Context 다.

    Activity Context 다!

    MainActivity Context 다!!

    결론 : 우리는 Context 라는 성을 가진 Context 가문인것이다.

     

    따라서 괄호 안에 매개인자로 Context 를 요구하면, 해당 가문의 자식이라면 누구든 기재할 수 있는것이다.

    "그렇다면 매개인자에 Context 가 나오면 무조건 this 를 쓰면 된다?"

    맞는말이... 아닌데? Context 를 쓰랬다고 무조건 this 를 사용하면 익명의 this가 될 수 있으니 주의해야한다.

    이부분은 밑에서 다뤄보자.

     

     

    그렇다면 왜 this를 쓰는건지에 대해 확실하게 알아야겠다. Danbi 라는 클래스가 있고, 이 클래스 안에는 say 라는 메소드가 있다. 이 메소드는 매개인자로 ContextThemeWrapper 를 요구하고 있다.

    class Danbi { 
      public void say(ContextThemeWrapper){ }
    }

     

    이때, 메인에서는 "Danbi 클래스에서 정의해놓은 say 메소드를 사용하고싶다!" 고 한다.

    say 메소드는 매개인자로 Context 를 줘야하고, MainActivity 는 Context 니까 this 쓰면 되겠지?

    class MainActivity extends Activity{
       new View.onClick(View v){
       say(this);
      }
    }

     

     

    say : "지금 말하는 this가 View.onClick 을 말하는거야.. MainActivity 를 말하는거야? 확실하게 해줘야지"

    say 에게는 자신을 감싸고 있는 두가지의 선택지가 있을때 this가 정확히 누구인지 구분할 수 있는 능력이 없다.

    위에 한가지의 선택지가 있을 경우에만 this 를 사용할 수 있는것이다.

    class MainActivity extends Activity{
       new View.onClick(View v){
       say(this);
      }
    }

     

     

    MainActivity : "내가 말하는 this 는 나 Context 를 말하는거야."

    say : "그렇군."

    class MainActivity extends Activity{
       new View.onClick(View v){
       say(MainActivity.this);
      }
    }

     

     

    그러니 현재 이! Context! 라고 확실하게 말해주자.

    Toast.makeText(this, "closing the application", Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this, "closing the application", Toast.LENGTH_SHORT).show();
    this 위에 Context 하나밖에 없을때 this 위에 Context 외에 잡다한것이 섞여 있을때

     

     

    'BACK-END > Android' 카테고리의 다른 글

    [Android] Fragment 사용하기 2  (0) 2020.11.11
    [Android] Fragment 사용하기 1  (0) 2020.11.11
    [Android] Method  (0) 2020.11.10
    [Android] permission  (0) 2020.11.10
    [Android] 다른문서로 배열 넘기기 / 영화 투표  (0) 2020.11.10

    댓글

Today
Designed by Danbee Park.