본문 바로가기

Develop/Android

Android CustomView 만드는 방법 (Java) #2

반응형
지난 글에 이어 더 심화(?)적인 내용으로 다음과 같이 다뤄보려 한다.
- Custom Listener
- Custom Attibute

 

Custom Listener

CustomView에서 직접 응답을 하도록 만들 수도 있지만 가장 좋은 것은 사용하는 시점마다 액션이 다를 수 있다는 점을 감안하여 동적으로 액션대응 하는 것이다. 그러다 보면 OnClickListener와 같은 기본 Listener를 사용하지 못하는 경우가 있는데 직접 만들 수도 있다.

  1. Java Interface를 활용하여 필요한 액션을 나열
  2. 액션이 필요한 View사용시점에서 Listener 정의.
  3. View에 Listener 셋팅.
1
2
3
4
5
public interface ButtonClickListener
{
    void onClick(View v);
}

Listener Interface 정의.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MainActivity extends AppCompatActivity
{
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        ButtonClickListener buttonClickListener = new ButtonClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //TODO
            }
        };
        
        ProfileView profileView = findViewById(R.id.profile);
        profileView.setReportListener(buttonClickListener);
    }
}

Listener 정의, 셋팅

1
2
3
4
5
6
7
8
9
10
11
12
public void setReportListener(ButtonClickListener listener){
        this.clickListener = listener;
 
        vBtnReport.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                clickListener.onClick(v);
            }
        });
    }
 

셋팅한 Listener는 실제 이벤트가 일어나는 위치에서 전달자 역할을 하도록 정의

 

 

Custom Attribute (XML init)

TextView같은 View들을 xml에서 사용할때 크기나 기본 텍스트 등을 입력할때 사용하던 기능이다.
ex) android:text="신고"
간단히 만들고 있던 ProfileView의 신고 버튼 유무를 만들어보려한다.

  • attrs.xml 생성

  1. values->attrs.xml 생성
  2. CustomView에서 사용할 attr 영역 생성
  3. attr추가
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ProfileView">
        <attr name="buttonVisible" format="boolean"/>
    </declare-styleable>
</resources>
 
  • 값 가져오기

1
2
3
4
5
6
7
8
9
10
11
12
public ProfileView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
 
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ProfileView);
        try{
            ta.getBoolean(R.styleable.ProfileView_buttonVisible, true);
        }finally
        {
            setup();
        }
    }

특별한 설명은 필요 없을 것 같다.
ProfileView 라는 attr의 네임스페이스를 import 한다는 느낌으로 사용하며, 값이 설정되지 않을 경우를 위해서 default값을 함께 입력해야한다.

다만, 속성 포맷으로 여러가지가 있으니 상황에 맞게 잘 활용해야한다.
https://stackoverflow.com/questions/3441396/defining-custom-attrs

 

Defining custom attrs

I need to implement my own attributes like in com.android.R.attr Found nothing in official documentation so I need information about how to define these attrs and how to use them from my code.

stackoverflow.com

 

 

반응형