XML 및 Java 코드를 통해 OnClickListener 인터페이스를 사용하는 것은 어떻게 다릅니 까?
저는 Android 개발에 익숙하지 않았고 처음 시작할 때 필요한 방법으로 xml 레이아웃을 사용하지 않으려 고했습니다. 그래서 이전 프로젝트 중 일부는 OnClickListener를 명시 적으로 생성하고 익명 내부 클래스로 구현하는 버튼을 포함하고 있습니다. -
final Button button = new Button(this);
button.setText("Click to change second line of text");
OnClickListener buttonListener = new View.OnClickListener() {
boolean clicked = false;
int numClicks = 0;
@Override
public void onClick(View v) {
if(numClicks > 5) {
button.setText("STOP IT");
}
numClicks++;
if(clicked == false){
clicked = true;
tv2.setText("Text Changed on Button Click");
}
else
{
clicked = false;
tv2.setText("Click again");
}
}
};
button.setOnClickListener(buttonListener);
하지만 안드로이드에 익숙해지면서 xml 레이아웃의 가치를 이해하기 시작했고 이와 같은 버튼을 구현했습니다.
<Button
android:id="@+id/button1"
android:layout_height = "wrap_content"
android:layout_width ="wrap_content"
android:text = "lets do this"
android:onClick = "DoIt"
/>
레이아웃 xml에서 DoIt이 java.
제 질문은이 두 가지 방법이 기능적으로 동일한가요? 장면 뒤 어딘가에 컴파일러에 의해 정의되는 OnClickListener가 있습니까? 어떤 방법을 사용하여 트레이드 오프하는 기능이 있습니까?
이것들은 똑같습니다. android:onClick
API 레벨 4에 추가되어보다 쉽고 자바 스크립트 웹과 유사하며 XML에서 모든 것을 구동 할 수 있습니다. 내부적으로하는 일은 메서드 OnClickListener
를 호출하는 Button을 추가하는 DoIt
것입니다.
다음은 android:onClick="DoIt"
내부적으로 a를 사용하는 것입니다 .
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoIt(v);
}
});
android:onClick
XML 구성에서 평소와 같이 를 사용하여 트레이드 오프 할 수있는 유일한 점 은 동적 콘텐츠를 추가하기가 조금 더 어려워진다는 것입니다 (프로그래밍 방식으로 변수에 따라 하나 또는 다른 리스너를 추가하도록 결정할 수 있음). 그러나 이것은 DoIt
메서드 내에 테스트를 추가하면 쉽게 무력화됩니다 .
XML을 사용하여 onclick 리스너를 직접 설정해야합니다. 먼저 클래스 implements OnClickListener
를 가지고 변수 Button button1;
를 추가 한 다음onCreate()
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
when you implement OnClickListener you need to add the inherited method onClick()
where you will handle your clicks
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
'programing tip' 카테고리의 다른 글
Apache POI 잠금 헤더 행 (0) | 2020.11.08 |
---|---|
ARM에서 SP (스택) 및 LR이란 무엇입니까? (0) | 2020.11.08 |
iOS에서 [Class new]와 [[Class alloc] init]의 차이점은 무엇입니까? (0) | 2020.11.07 |
Visual Studio를 처음 시작하는 데 시간이 오래 걸립니다. (0) | 2020.11.07 |
동일한 순서로 한 번에 두 목록을 섞습니다. (0) | 2020.11.07 |