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


134

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

Answers:


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); 创建Button对象的方法。
卡迪尔·侯赛因

2
您可以在MyButton类中添加一个新方法:void setMyListener(MyListner m1){this.ml = m1;},然后随时使用此方法设置您的侦听器对象。
Rakesh Soni 2015年

1
此方法在哪里使用MyLogicToIntimateOthere()?
abh22ishek '16

1
来自iOS背景,如果我在iOS中执行此操作,则会导致内存泄漏,因为MyButton的侦听器是对侦听器的强引用,而侦听器对MyButton的强引用是Java垃圾回收器,足够聪明知道如果除了MyButton之外没有其他对侦听器的引用,应该同时清理侦听器和MyButton吗?WeakReference<>在这种情况下,您可以使用a ,但是您不能使该侦听器成为匿名类或该侦听器没有其他引用的任何内容……因此最好不要使用它
Fonix

其中是MyLogicToIntimateOthers()中使用
抗体

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

我创建了一个通用AsyncTask侦听器,该侦听器从AsycTask独立类获取结果,并使用接口回调将其提供给CallingActivity。

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.创建接口类(监听器)

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

3实现视图2的接口(视图2中使用的视图1)

4.在视图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;
}

从您的First活动中调用此方法,然后传递侦听器接口...


4

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

现在在您的驱动程序类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

在Android中,您可以创建一个接口(例如Listener),然后您的Activity会实现该接口,但是我认为这不是一个好主意。如果我们有许多组件可以侦听它们状态的变化,则可以创建一个BaseListener实现接口Listener,并使用类型代码来处理它们。我们可以在创建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

执行此方法的简单方法。首先OnClickListeners在您的Activity类中实现。

码:

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;
        }
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.