안드로이드 컴스텀뷰만들 때 생성자 질문드립니다.

조회수 4811회

Custom뷰를 만들때 다른 레이아웃을 상속받게되면 아래 생성자를 구현해야 하는 걸로 알고있는데요 이중 defStyleAttr와 defStyleRes 파라메터가 왜 필요하고 어떤 곳에 사용이 되는지 궁금합니다.~ 가능하시다면 사용법도 알려주시면 감사합니다!

public MyView(Context context) {
    super(context);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • defStyleAttr은 뷰의 기본적인 속성들을 지정하기 위한 파라미터입니다. EditText의 생성자 코드를 보면 다음과 같이 정의되는 것을 알 수 있는데요.

    public class EditText extends TextView {
        public EditText(Context context) {
            this(context, null);
        }
    
        public EditText(Context context, AttributeSet attrs) {
            this(context, attrs, com.android.internal.R.attr.editTextStyle);
        }
    
        public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
            this(context, attrs, defStyleAttr, 0);
        }
    
        public EditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        ...
    }
    

    두번째 생성자를 보면 this()를 통해 세번째 생성자를 호출하는 것을 확인할 수 있습니다. defStyleAttr로 넘겨지는 com.android.internal.R.attr.editTextStyle에 정의되어 있는 속성은 다음과 같이 부여되어 있는 것을 알 수 있습니다.

    <style name="Widget.EditText">
        <item name="focusable">true</item>
        <item name="focusableInTouchMode">true</item>
        <item name="clickable">true</item>
        <item name="background">?attr/editTextBackground</item>
        <item name="textAppearance">?attr/textAppearanceMediumInverse</item>
        <item name="textColor">?attr/editTextColor</item>
        <item name="gravity">center_vertical</item>
        <item name="breakStrategy">simple</item>
        <item name="hyphenationFrequency">normal</item>
    </style>
    

    EditText가 TextView를 상속받고 있지만 EditText 고유의 속성을 defStyleAttr을 통해 View 생성 시점에 설정한다고 이해하면 쉬울 것 같고요. defStyleAttr과 defStyleRes 차이는 R.attr.XXX와 R.style.XXX을 넘기느냐의 차이입니다.

    관련 예제는 아래 링크를 참고하세요.

    http://www.programering.com/a/MjNwATNwATg.html

    • (•́ ✖ •̀)
      알 수 없는 사용자
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)