如何在android中创建自己的Listener接口?

Raj*_*ian 125 android

有人可以帮助我用一些代码片段创建用户定义的监听器界面吗?

Rak*_*oni 184

创建一个新文件:

MyListener.java:

public interface MyListener {
    // you can define any parameter as per your requirement
    public void callback(View view, String result);
}
Run Code Online (Sandbox Code Playgroud)

在您的活动中,实现界面:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的自定义类中,在需要时调用接口:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我们的Button已经在布局中而不是使用MyButton,那么如何传递侦听器对象; m = new MyButton(this); 创建Button对象的方法。 (2认同)
  • 您可以在MyButton类中添加一个新方法:void setMyListener(MyListner m1){this.ml = m1;}然后随时使用此方法设置您的侦听器对象. (2认同)
  • 来自 iOS 背景,如果我在 iOS 中这样做会导致内存泄漏,因为 MyButton 的侦听器是对侦听器的强引用,而侦听器对 MyButton 有强引用...... java 垃圾收集器是否足够聪明知道如果除了 MyButton 之外没有对侦听器的引用,应该清除侦听器和 MyButton 吗?在这种情况下,您可以使用 `WeakReference<>`,但是您不能使侦听器成为匿名类或任何侦听器没有其他引用的东西......所以最好不要使用它 (2认同)

Rup*_*esh 102

请阅读观察者模式

监听器接口

public interface OnEventListener {
    void onEvent(EventResult er);
    // or void onEvent(); as per your need
}
Run Code Online (Sandbox Code Playgroud)

那么在你的类说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 :)
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的驱动程序类中 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Xar*_*han 10

我创建了一个Generic AsyncTask Listener,它从AsycTask seperate类获取结果,并使用Interface Callback将其提供给CallingActivity.

new GenericAsyncTask(context,new AsyncTaskCompleteListener()
        {
             public void onTaskComplete(String response) 
             {
                 // do your work. 
             }
        }).execute();
Run Code Online (Sandbox Code Playgroud)

接口

interface AsyncTaskCompleteListener<T> {
   public void onTaskComplete(T result);
}
Run Code Online (Sandbox Code Playgroud)

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);
   }  
}
Run Code Online (Sandbox Code Playgroud)

看看这个,这个问题有更多细节.


Ras*_*iri 7

有4个步骤:

1.create接口类(监听器)

2.在视图1中使用接口(定义变量)

3.implements接口到视图2(视图2中使用的视图1)

4.在视图1中通过界面查看2

例:

第1步:您需要创建界面和definde功能

public interface onAddTextViewCustomListener {
    void onAddText(String text);
}
Run Code Online (Sandbox Code Playgroud)

第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");
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

创建监听器接口.

public interface YourCustomListener
{
    public void onCustomClick(View view);
            // pass view as argument or whatever you want.
}
Run Code Online (Sandbox Code Playgroud)

并在另一个活动(或片段)中创建方法setOnCustomClick,您要在其中应用自定义侦听器......

  public void setCustomClickListener(YourCustomListener yourCustomListener)
{
    this.yourCustomListener= yourCustomListener;
}
Run Code Online (Sandbox Code Playgroud)

从First活动中调用此方法,并传递侦听器接口...


The*_*her 6

到了2018年,监听器接口就不再需要了。Android LiveData 负责将所需结果传递回 UI 组件。

如果我采用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在您的驱动程序类 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.
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息以及代码示例,您可以阅读我的文章以及官方文档:

何时以及为何使用 LiveData

官方文档