Difference between OnClick() event and OnClickList

2019-01-09 03:32发布

I'm always using onclick() event in most of my projects. But, I read about OnClickListener(). Can anyone tell what's the difference between these two? And which one is best to use in Android application?.

15条回答
仙女界的扛把子
2楼-- · 2019-01-09 03:37

everyone has mentioned about OnClickListener listner which one always used. i want to add one more point android:onClick works as method and it's doesn't need to be reference so it's useful when you have to add button after some task executed so you cant't referenced it for OnClickListener.

For an example when we create viewpager with only layout (no fragments) if you put an button in any layout it insialized only when layout visible so you can't use method findViewById for Button in that case android:onClick becomed useful just put that method in activity!!

查看更多
神经病院院长
3楼-- · 2019-01-09 03:41

You can add android:onClick="your_method" attribute in your XML.

Example:

 <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Click"
  android:onClick="your_method"/>
查看更多
何必那么认真
4楼-- · 2019-01-09 03:41

When we want to add click listener to button in Java code, we use OnClickListener.
When we want to add click listener to button in the layout file, we useandroid:onClick="your_method"
If you use XML variant, you must implement your_method in your app class.

查看更多
forever°为你锁心
5楼-- · 2019-01-09 03:43

I'm not sure the question is clear. View.OnClickListener is an interface, which defines the onClick(View) method. If you have a class which intends to listen for clicks, you should both implement the interface (if not already extending a class that does), and implement this method too. You have to use both; they're not somehow alternatives.

查看更多
不美不萌又怎样
6楼-- · 2019-01-09 03:43

Here is the simple terminology If u are at home and U want to call someone..u can call directly and they can listen u. (use onclick). But if u are outside and u want to Call someone at home u need to use either phone or Internet.(need to use onclicklistener). In Android everything starts from home, I.e. main_activity This is the way android eases yr work ; when u have one activity u don't have to attach a listener, create object, and define it. Just use onClick. Onclicklistener are generally used in Fragments. So Keep Coding.

查看更多
We Are One
7楼-- · 2019-01-09 03:44
Button button = (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do stuff
    }
});

OnClickListener is an interface and onClick is method of OnClickListener.

查看更多
登录 后发表回答