지난 글에 이어 더 심화(?)적인 내용으로 다음과 같이 다뤄보려 한다.
- Custom Listener
- Custom Attibute
Custom Listener
CustomView에서 직접 응답을 하도록 만들 수도 있지만 가장 좋은 것은 사용하는 시점마다 액션이 다를 수 있다는 점을 감안하여 동적으로 액션대응 하는 것이다. 그러다 보면 OnClickListener와 같은 기본 Listener를 사용하지 못하는 경우가 있는데 직접 만들 수도 있다.
- Java Interface를 활용하여 필요한 액션을 나열
- 액션이 필요한 View사용시점에서 Listener 정의.
- 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 생성
- values->attrs.xml 생성
- CustomView에서 사용할 attr 영역 생성
- 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
반응형
'Develop > Android' 카테고리의 다른 글
Android Studio 업그레이드 (2) | 2024.01.15 |
---|---|
Singleton VS Application class (0) | 2019.09.04 |
Android CustomView 만드는 방법 (Java) (0) | 2019.07.22 |
AndroidX 마이그레이션 방법 (0) | 2019.07.12 |
[CustomView] TextView를 이용한 SNS 더보기 기능 (0) | 2019.07.07 |