如何在 android 中创建我们自己的监听器接口?

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

234870 次浏览

创建侦听器接口。

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 活动调用此方法,并传递侦听器接口..。

请阅读 观察者模式

监听器接口

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

创建一个新文件:

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

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

返回文章页面

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

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

但我不认为这是个好主意。

我已经创建了一个 Generic 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);
}
}

看看 这个这个问题了解更多细节。

这个方法很简单。首先在你的 Activity 类中实现 OnClickListeners

密码:

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

有四个步骤:

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

在2018年,不再需要侦听器接口。您已经让 AndroidLiveData 负责将所需的结果传递回 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

官方文件

我已经做了类似下面的事情,把我的模型类从第二个活动发送到第一个活动。我使用 LiveData 来实现这一点,得到了 Rupesh 和 TheCodefather 的答案的帮助。

第二项活动

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

希望这对像我这样的新探险家有所帮助。