답변:
새 파일을 작성하십시오.
MyListener.java:
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, String result);
}
활동에서 인터페이스를 구현하십시오.
MyActivity.java:
public class MyActivity extends Activity implements MyListener {
@override
public void onCreate(){
MyButton m = new MyButton(this);
}
// method is invoked when MyButton is clicked
@override
public void callback(View view, String result) {
// do your stuff here
}
}
사용자 정의 클래스에서 필요한 경우 인터페이스를 호출하십시오.
MyButton.java:
public class MyButton {
MyListener ml;
// constructor
MyButton(MyListener ml) {
//Setting the listener
this.ml = ml;
}
public void MyLogicToIntimateOthers() {
//Invoke the interface
ml.callback(this, "success");
}
}
WeakReference<>이 경우에는을 사용할 수 있지만 리스너를 익명 클래스 또는 리스너에 다른 참조가없는 항목으로 만들 수는 없습니다. 따라서 사용하지 않는 것이 좋습니다.
관찰자 패턴을 읽으십시오
리스너 인터페이스
public interface OnEventListener {
void onEvent(EventResult er);
// or void onEvent(); as per your need
}
다음 클래스 말의에 Event클래스
public class Event {
private OnEventListener mOnEventListener;
public void setOnEventListener(OnEventListener listener) {
mOnEventListener = listener;
}
public void doEvent() {
/*
* code code code
*/
// and in the end
if (mOnEventListener != null)
mOnEventListener.onEvent(eventResult); // event result object :)
}
}
운전석에서 MyTestDriver
public class MyTestDriver {
public static void main(String[] args) {
Event e = new Event();
e.setOnEventListener(new OnEventListener() {
public void onEvent(EventResult er) {
// do your work.
}
});
e.doEvent();
}
}
AsycTask 별도 클래스에서 결과를 얻고 인터페이스 콜백을 사용하여 CallingActivity에 제공하는 일반 AsyncTask 리스너를 작성했습니다.
new GenericAsyncTask(context,new AsyncTaskCompleteListener()
{
public void onTaskComplete(String response)
{
// do your work.
}
}).execute();
상호 작용
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result);
}
GenericAsyncTask
class GenericAsyncTask extends AsyncTask<String, Void, String>
{
private AsyncTaskCompleteListener<String> callback;
public A(Context context, AsyncTaskCompleteListener<String> cb) {
this.context = context;
this.callback = cb;
}
protected void onPostExecute(String result) {
finalResult = result;
callback.onTaskComplete(result);
}
}
4 단계가 있습니다.
1. 인터페이스 클래스 생성 (리스너)
보기 1의 인터페이스 사용 (변수 정의)
보기 2에 대한 인터페이스 구현 (보기 2에서 사용 된보기 1)
보기 1의 인터페이스를 통과하여보기 2
예:
1 단계 : 인터페이스 작성 및 정의 기능이 필요합니다.
public interface onAddTextViewCustomListener {
void onAddText(String text);
}
2 단계 :이 인터페이스 사용
public class CTextView extends TextView {
onAddTextViewCustomListener onAddTextViewCustomListener; //listener custom
public CTextView(Context context, onAddTextViewCustomListener onAddTextViewCustomListener) {
super(context);
this.onAddTextViewCustomListener = onAddTextViewCustomListener;
init(context, null);
}
public CTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
public void init(Context context, @Nullable AttributeSet attrs) {
if (isInEditMode())
return;
//call listener
onAddTextViewCustomListener.onAddText("this TextView added");
}
}
3,4 단계 : 활동 구현
public class MainActivity extends AppCompatActivity implements onAddTextViewCustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get main view from layout
RelativeLayout mainView = (RelativeLayout)findViewById(R.id.mainView);
//create new CTextView and set listener
CTextView cTextView = new CTextView(getApplicationContext(), this);
//add cTextView to mainView
mainView.addView(cTextView);
}
@Override
public void onAddText(String text) {
Log.i("Message ", text);
}
}
리스너 인터페이스를 만듭니다.
public interface YourCustomListener
{
public void onCustomClick(View view);
// pass view as argument or whatever you want.
}
그리고 사용자 정의 리스너를 적용하려는 다른 활동 (또는 조각)에서 setOnCustomClick 메소드를 작성하십시오 ...
public void setCustomClickListener(YourCustomListener yourCustomListener)
{
this.yourCustomListener= yourCustomListener;
}
첫 번째 활동에서이 메소드를 호출하고 리스너 인터페이스를 전달하십시오.
2018 년에는 리스너 인터페이스가 필요하지 않습니다. 원하는 결과를 UI 구성 요소로 다시 전달하는 데 필요한 Android LiveData가 있습니다.
Rupesh의 답변을 받아 LiveData를 사용하도록 조정하면 다음과 같습니다.
public class Event {
public LiveData<EventResult> doEvent() {
/*
* code code code
*/
// and in the end
LiveData<EventResult> result = new MutableLiveData<>();
result.setValue(eventResult);
return result;
}
}
그리고 이제 드라이버 클래스 MyTestDriver에서 :
public class MyTestDriver {
public static void main(String[] args) {
Event e = new Event();
e.doEvent().observe(this, new Observer<EventResult>() {
@Override
public void onChanged(final EventResult er) {
// do your work.
}
});
}
}
코드 샘플과 함께 자세한 내용은 공식 문서뿐만 아니라 해당 게시물을 읽을 수 있습니다.
안드로이드에서는 리스너와 같은 인터페이스를 만들 수 있으며 액티비티가 구현하지만 좋은 생각은 아닙니다. 상태 변경을 수신 할 컴포넌트가 많은 경우 BaseListener 구현 인터페이스 리스너를 작성하고 유형 코드를 사용하여 처리 할 수 있습니다. XML 파일을 만들 때 메소드를 바인딩 할 수 있습니다. 예를 들면 다음과 같습니다.
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4"
android:onClick="Btn4OnClick" />
그리고 소스 코드 :
public void Btn4OnClick(View view) {
String strTmp = "点击Button04";
tv.setText(strTmp);
}
그러나 나는 그것이 좋은 생각이라고 생각하지 않습니다 ...
모델 클래스를 두 번째 활동에서 첫 번째 활동으로 보내기 위해 다음과 같은 작업을 수행했습니다. Rupesh와 TheCodeFather의 답변을 통해 LiveData를 사용하여이를 달성했습니다.
두 번째 활동
public static MutableLiveData<AudioListModel> getLiveSong() {
MutableLiveData<AudioListModel> result = new MutableLiveData<>();
result.setValue(liveSong);
return result;
}
"liveSong"은 전 세계적으로 선언 된 AudioListModel입니다.
첫 번째 활동에서이 메소드를 호출하십시오.
PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
@Override
public void onChanged(AudioListModel audioListModel) {
if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
}
}
});
나와 같은 새로운 탐험가들에게 도움이 되길 바랍니다.
이 방법을 수행하는 간단한 방법. 먼저 OnClickListenersActivity 클래스에서를 구현합니다 .
암호:
class MainActivity extends Activity implements OnClickListeners{
protected void OnCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.activity_main.xml);
Button b1=(Button)findViewById(R.id.sipsi);
Button b2=(Button)findViewById(R.id.pipsi);
b1.SetOnClickListener(this);
b2.SetOnClickListener(this);
}
public void OnClick(View V)
{
int i=v.getId();
switch(i)
{
case R.id.sipsi:
{
//you can do anything from this button
break;
}
case R.id.pipsi:
{
//you can do anything from this button
break;
}
}
}