Android에서 자체 리스너 인터페이스를 만드는 방법은 무엇입니까?


134

누군가가 코드 스 니펫으로 사용자 정의 리스너 인터페이스를 만드는 데 도움을 줄 수 있습니까?

답변:


198

새 파일을 작성하십시오.

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");
    }
}

2
Button이 이미 레이아웃에있는 경우 리스너 객체를 전달하는 방법 대신 MyButton을 사용하지 않습니다. m = new MyButton (this); 버튼의 객체를 만드는 방법.
카디르 후세인

2
MyButton 클래스에 새 메소드를 추가 할 수 있습니다. void setMyListener (MyListner m1) {this.ml = m1;} 그리고 언제든지이 메소드를 사용하여 리스너 객체를 설정할 수 있습니다.
Rakesh Soni

1
이 메소드가 사용 된 MyLogicToIntimateOthere ()는 어디에 있습니까?
abh22ishek 2016 년

1
iOS 배경에서 오는 경우, iOS 에서이 작업을 수행하면 MyButton의 리스너가 리스너에 대한 강력한 참조이며 리스너가 MyButton에 대한 강력한 참조를 가지고 있기 때문에 메모리 누수가 발생합니다. MyButton 이외의 리스너에 대한 참조가없는 경우 리스너와 MyButton을 모두 정리해야한다는 것을 알고 있습니까? WeakReference<>이 경우에는을 사용할 수 있지만 리스너를 익명 클래스 또는 리스너에 다른 참조가없는 항목으로 만들 수는 없습니다. 따라서 사용하지 않는 것이 좋습니다.
Fonix

여기서 ()를 사용 MyLogicToIntimateOthers 인
Ab의

109

관찰자 패턴을 읽으십시오

리스너 인터페이스

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();
    }
}

11

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);
   }  
}

한 번 봐 가지고 , 이 질문에 자세한 내용을.


8

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);
    }
}

7

리스너 인터페이스를 만듭니다.

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;
}

첫 번째 활동에서이 메소드를 호출하고 리스너 인터페이스를 전달하십시오.


4

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.
            }
        });
    }
}

코드 샘플과 함께 자세한 내용은 공식 문서뿐만 아니라 해당 게시물을 읽을 수 있습니다.

언제 그리고 왜 LiveData를 사용해야합니까

공식 문서


0

안드로이드에서는 리스너와 같은 인터페이스를 만들 수 있으며 액티비티가 구현하지만 좋은 생각은 아닙니다. 상태 변경을 수신 할 컴포넌트가 많은 경우 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);  
    }  

그러나 나는 그것이 좋은 생각이라고 생각하지 않습니다 ...


0

모델 클래스를 두 번째 활동에서 첫 번째 활동으로 보내기 위해 다음과 같은 작업을 수행했습니다. 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());
                }
            }
        });

나와 같은 새로운 탐험가들에게 도움이 되길 바랍니다.


-4

이 방법을 수행하는 간단한 방법. 먼저 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;
        }
    }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.