Android : 버튼 클릭 처리 방법
비 Java 및 비 Android 영역에서 탄탄한 경험을 쌓은 저는 Android를 배우고 있습니다.
다른 영역과 많은 혼동이 있습니다. 그중 하나는 버튼 클릭을 처리하는 방법입니다. 최소한 4 가지 방법 (!!!)이 있으며 여기에 간략하게 나열되어 있습니다.
일관성을 위해 다음과 같이 나열합니다.
View.OnClickListener
활동에 클래스 의 멤버를onClick
두고onCreate
활동 메소드의 논리를 처리 할 인스턴스에 할당합니다 .'onCreate'액티비티 메서드에서 'onClickListener'를 생성하고 setOnClickListener를 사용하여 버튼에 할당합니다.
활동 자체에서 'onClickListener'를 구현하고 'this'를 버튼의 리스너로 지정하십시오. 활동에 버튼이 적은 경우 버튼 ID를 분석하여 적절한 버튼에 대한 'onClick'핸들러를 실행해야합니다.
'onClick'로직을 구현하는 활동에 대한 공용 메소드를 가지고 활동 xml 선언의 단추에 할당합니다.
질문 1:
그 모든 방법이 있습니까? 다른 옵션이 있습니까? (다른 건 필요 없어 그냥 궁금해)
나에게 가장 직관적 인 방법은 최신 방법 일 것입니다. 입력 할 코드의 양이 가장 적고 가장 읽기 쉽습니다 (적어도 나에게는).
하지만이 접근 방식이 널리 사용되는 것은 아닙니다. 그것을 사용하는 것에 대한 단점은 무엇입니까?
질문 # 2 :
이러한 각 방법의 장단점은 무엇입니까? 귀하의 경험이나 좋은 링크를 공유하십시오.
모든 피드백을 환영합니다!
추신 : Google에이 주제에 대한 무언가를 찾아 보려고했지만 내가 찾은 유일한 것은 "어떻게"그 일을 수행하는지 설명하는 것이지 왜 좋은지 나쁜지가 아닙니다.
질문 1 : 안타깝게도 당신이 가장 직관적이라고 말하는 것은 안드로이드에서 가장 적게 사용되는 것입니다. 이해했듯이 UI (XML)와 계산 기능 (Java 클래스 파일)을 분리해야합니다. 또한 더 쉽게 디버깅 할 수 있습니다. 실제로 이런 식으로 읽고 Android imo에 대해 생각하는 것이 훨씬 쉽습니다.
질문 2 : 주로 사용되는 두 가지는 # 2와 # 3이라고 생각합니다. 예를 들어 Button clickButton을 사용하겠습니다.
2
익명 클래스의 형태입니다.
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
***Do what you want with the click here***
}
});
이것은 findViewById로 버튼 변수가 설정된 바로 옆에 onClick 메서드가 있기 때문에 제가 가장 좋아하는 것입니다. 이 clickButton Button View를 다루는 모든 것이 여기에 있다는 것이 매우 깔끔하고 깔끔해 보입니다.
내 동료가 언급 한 단점은 onclick 리스너가 필요한 뷰가 많다는 것입니다. onCreate의 길이가 매우 길다는 것을 알 수 있습니다. 그래서 그가 사용하는 것을 좋아하는 이유 :
삼
5 개의 clickButton이 있다고 가정 해 보겠습니다.
Activity / Fragment가 OnClickListener를 구현하는지 확인하십시오.
// in OnCreate
Button mClickButton1 = (Button)findViewById(R.id.clickButton1);
mClickButton1.setOnClickListener(this);
Button mClickButton2 = (Button)findViewById(R.id.clickButton2);
mClickButton2.setOnClickListener(this);
Button mClickButton3 = (Button)findViewById(R.id.clickButton3);
mClickButton3.setOnClickListener(this);
Button mClickButton4 = (Button)findViewById(R.id.clickButton4);
mClickButton4.setOnClickListener(this);
Button mClickButton5 = (Button)findViewById(R.id.clickButton5);
mClickButton5.setOnClickListener(this);
// somewhere else in your code
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickButton1: {
// do something for button 1 click
break;
}
case R.id.clickButton2: {
// do something for button 2 click
break;
}
//.... etc
}
}
내 동료가 설명하는이 방법은 모든 onClick 계산이 onCreate 메소드를 복잡하게하지 않고 한곳에서 처리되기 때문에 그의 눈에 더 깔끔합니다. 그러나 내가 보는 단점은 다음과 같습니다.
- 자신을 바라보고
- onClick 메서드에서 사용하는 onCreate에있을 수있는 다른 개체는 필드로 만들어야합니다.
더 많은 정보를 원하시면 알려주세요. 꽤 긴 질문이기 때문에 귀하의 질문에 완전히 대답하지 않았습니다. 그리고 사이트를 찾으면 답을 넓힐 것입니다. 지금은 경험을 제공하고 있습니다.
#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).
If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.
For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).
#2 Pros and cons for all methods are almost the same and the lesson should be:
Use what ever is most appropriate or feels most intuitive to you.
If you have to assign the same OnClickListener
to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Take action.
}
});
I tend to not implement the OnClickListener
in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this
is all doing).
I prefer option 4, but it makes intuitive sense to me because I do far too much work in Grails, Groovy, and JavaFX. "Magic" connections between the view and the controller are common in all. It is important to name the method well:
In the view,add the onClick method to the button or other widget:
android:clickable="true"
android:onClick="onButtonClickCancel"
Then in the class, handle the method:
public void onButtonClickCancel(View view) {
Toast.makeText(this, "Cancel pressed", Toast.LENGTH_LONG).show();
}
Again, name the method clearly, something you should do anyway, and the maintenance becomes second-nature.
One big advantage is that you can write unit tests now for the method. Option 1 can do this, but 2 and 3 are more difficult.
Most used way is, anonymous declaration
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// handle click
}
});
Also you can create View.OnClickListener object and set it to button later, but you still need to override onClick method for example
View.OnClickListener listener = new View.OnClickListener(){
@Override
public void onClick(View v) {
// handle click
}
}
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(listener);
When your activity implements OnClickListener interface you must override onClick(View v) method on activity level. Then you can assing this activity as listener to button, because it already implements interface and overrides the onClick() method
public class MyActivity extends Activity implements View.OnClickListener{
@Override
public void onClick(View v) {
// handle click
}
@Override
public void onCreate(Bundle b) {
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(this);
}
}
(imho) 4-th approach used when multiple buttons have same handler, and you can declare one method in activity class and assign this method to multiple buttons in xml layout, also you can create one method for one button, but in this case I prefer to declare handlers inside activity class.
Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.
My sample, Tested in Android studio 2.1
Define button in xml layout
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java pulsation detect
Button clickButton = (Button) findViewById(R.id.btn1);
if (clickButton != null) {
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
/***Do what you want with the click here***/
}
});
}
To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class
//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
// handle click
});
but if you wish to apply click event to your button at once in a method.
you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener
.
In other to use Question #3 properly
Question#1 - These are the only way to handle view clicks.
Question#2 -
Option#1/Option#4 - There's not much difference between option#1 and option#4. The only difference I see is in one case activity is implementing the OnClickListener, whereas, in the other case, there'd be an anonymous implementation.
Option#2 - In this method an anonymous class will be generated. This method is a bit cumborsome, as, you'd need to do it multiple times, if you have multiple buttons. For Anonymous classes, you have to be careful for handling memory leaks.
Option#3 - Though, this is a easy way. Usually, Programmers try not to use any method until they write it, and hence this method is not widely used. You'd see mostly people use Option#4. Because it is cleaner in term of code.
There are also options available in the form of various libraries that can make this process very familiar to people that have used other MVVM frameworks.
https://developer.android.com/topic/libraries/data-binding/
Shows an example of an official library, that allows you to bind buttons like this:
<Button
android:text="Start second activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> presenter.showList()}"
/>
Step 1:Create an XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnClickEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Step 2:Create MainActivity:
package com.scancode.acutesoft.telephonymanagerapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
Button btnClickEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClickEvent = (Button) findViewById(R.id.btnClickEvent);
btnClickEvent.setOnClickListener(MainActivity.this);
}
@Override
public void onClick(View v) {
//Your Logic
}
}
HappyCoding!
참고URL : https://stackoverflow.com/questions/14782901/android-how-to-handle-button-click
'IT story' 카테고리의 다른 글
MySQL 데이터베이스의 모든 트리거를 어떻게 나열합니까? (0) | 2020.09.09 |
---|---|
MySQL에서 UNSIGNED 및 SIGNED INT를 언제 사용해야합니까? (0) | 2020.09.09 |
Python의 "스레드 로컬 저장소"란 무엇이며 왜 필요합니까? (0) | 2020.09.09 |
React Native에서 회전을 비활성화하는 방법은 무엇입니까? (0) | 2020.09.08 |
Java에서 두 세트를 비교하는 가장 빠른 방법은 무엇입니까? (0) | 2020.09.08 |