[英]How to create our own Listener interface in android?
有人可以帮助我使用一些代码片段创建用户定义的侦听器界面吗?
Create a new file:创建一个新文件:
MyListener.java
: MyListener.java
:
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, String result);
}
In your activity, implement the interface:在您的活动中,实现接口:
MyActivity.java
: 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
}
}
In your custom class, invoke the interface when needed:在您的自定义类中,在需要时调用接口:
MyButton.java
: 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");
}
}
please do read observer pattern请阅读观察者模式
listener interface监听接口
public interface OnEventListener {
void onEvent(EventResult er);
// or void onEvent(); as per your need
}
then in your class say Event
class然后在你的课上说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 :)
}
}
in your driver class MyTestDriver
在您的驱动程序类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();
}
}
I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.我创建了一个通用 AsyncTask 侦听器,它从 AsycTask 单独的类中获取结果,并使用接口回调将其提供给 CallingActivity。
new GenericAsyncTask(context,new AsyncTaskCompleteListener()
{
public void onTaskComplete(String response)
{
// do your work.
}
}).execute();
Interface界面
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);
}
}
Have a look at this , this question for more details.看看这个,这个问题了解更多细节。
There are 4 steps:有4个步骤:
1.create interface class (listener) 1.创建接口类(监听器)
2.use interface in view 1 (define variable) 2.在视图1中使用接口(定义变量)
3.implements interface to view 2 (view 1 used in view 2) 3.implements interface to view 2 (view 1用于view 2)
4.pass interface in view 1 to view 2 4.通过视图1到视图2的界面
Example:例子:
Step 1: you need create interface and definde function第 1 步:您需要创建接口和定义函数
public interface onAddTextViewCustomListener {
void onAddText(String text);
}
Step 2: use this interface in view第二步:在视图中使用这个接口
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");
}
}
Step 3,4: implements to activity步骤 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);
}
}
Create listener interface.创建监听器接口。
public interface YourCustomListener
{
public void onCustomClick(View view);
// pass view as argument or whatever you want.
}
And create method setOnCustomClick in another activity(or fragment) , where you want to apply your custom listener......并在另一个活动(或片段)中创建方法 setOnCustomClick ,您要在其中应用自定义侦听器......
public void setCustomClickListener(YourCustomListener yourCustomListener)
{
this.yourCustomListener= yourCustomListener;
}
Call this method from your First activity, and pass the listener interface...从您的第一个活动调用此方法,并传递侦听器接口...
In the year of 2018, there's no need for listeners interfaces. 2018年不需要监听接口。 You've got Android LiveData to take care of passing the desired result back to the UI components.您已经让 Android LiveData 负责将所需的结果传递回 UI 组件。
If I'll take Rupesh's answer and adjust it to use LiveData, it will like so:如果我接受 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;
}
}
and now in your driver class MyTestDriver:现在在您的驱动程序类 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.
}
});
}
}
For more information along with code samples you can read my post about it, as well as the offical docs:有关代码示例的更多信息,您可以阅读我关于它的帖子以及官方文档:
In Android,you can create an interface such as Listener,and your Activity implements it,but i don't think it is a good idea.在 Android 中,您可以创建一个接口,例如 Listener,然后您的 Activity 实现它,但我认为这不是一个好主意。 if we have many components to listen the changes of their state,we can create a BaseListener implements interface Listener,and use type code to handle them.如果我们有很多组件要监听它们状态的变化,我们可以创建一个BaseListener实现接口Listener,并使用类型代码来处理它们。 we can bind the method when we create XML file,for example:我们可以在创建 XML 文件时绑定方法,例如:
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4"
android:onClick="Btn4OnClick" />
and the source code:和源代码:
public void Btn4OnClick(View view) {
String strTmp = "点击Button04";
tv.setText(strTmp);
}
but i don't think it is a good idea...但我不认为这是一个好主意......
I have done it something like below for sending my model class from the Second Activity to First Activity.我已经做了类似下面的事情,将我的模型类从第二个活动发送到第一个活动。 I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.在 Rupesh 和 TheCodeFather 的帮助下,我使用 LiveData 来实现这一点。
Second Activity第二个活动
public static MutableLiveData<AudioListModel> getLiveSong() {
MutableLiveData<AudioListModel> result = new MutableLiveData<>();
result.setValue(liveSong);
return result;
}
"liveSong" is AudioListModel declared globally “liveSong”是全局声明的 AudioListModel
Call this method in the First Activity在第一个活动中调用此方法
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());
}
}
});
May this help for new explorers like me.愿这对像我这样的新探险家有所帮助。
Simple method to do this approach.做这个方法的简单方法。 Firstly implements the OnClickListeners
in your Activity class.首先在您的 Activity 类中实现OnClickListeners
。
Code:代码:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.