How to create our own Listener interface in android?

前端 未结 9 1918
不知归路
不知归路 2020-11-22 04:55

Could someone help me to create user defined listener interface with some code snippets?

相关标签:
9条回答
  • 2020-11-22 05:29

    There are 4 steps:

    1.create interface class (listener)

    2.use interface in view 1 (define variable)

    3.implements interface to view 2 (view 1 used in view 2)

    4.pass interface in view 1 to view 2

    Example:

    Step 1: you need create interface and definde function

    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

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:29

    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. 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. we can bind the method when we create XML file,for example:

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

    0 讨论(0)
  • 2020-11-22 05:32

    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

    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

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:32

    I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.

    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.

    0 讨论(0)
  • 2020-11-22 05:32

    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.

    Second Activity

    public static MutableLiveData<AudioListModel> getLiveSong() {
            MutableLiveData<AudioListModel> result = new MutableLiveData<>();
            result.setValue(liveSong);
            return result;
        }
    

    "liveSong" is AudioListModel declared globally

    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.

    0 讨论(0)
  • 2020-11-22 05:37

    Simple method to do this approach. Firstly implements the OnClickListeners in your Activity class.

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题