add android button's on click event in a separate class -


i have button in android have defined in fragment_main.xml -

<button     android:id="@+id/button1"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/love_button_text"      android:onclick="onlovebuttonclicked"     /> 

the main_activity xml file follows -

 <framelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.newa.newapp2.mainactivity" tools:ignore="mergerootframe"         >      <button     android:id="@+id/button2"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_margintop="100sp"     android:text="@string/a_button"      android:onclick="onlovebuttonclicked1"     /> </framelayout>  

now there onclick event defined wanted define in separate class file follows -

public class androidlove extends activity { @override public void oncreate(bundle savedinstancestate) {            super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);      }  public void onlovebuttonclicked1(view view) {            textview tv = (textview) findviewbyid(r.id.anothertext);             tv.setvisibility(view.visible);      }      } 

this compiles fine @ run time throws error

"could not find event listener named onlovebuttonclicked"

this working fine if write function in mainactivity.java

any ideas?

thanks

use anonymous inner class in fragment class.

@override public view oncreateview(layoutinflater inflater, viewgroup container,                          bundle savedinstancestate) {    view view = inflater.inflate(r.layout.fragment_main,             container, false);      button button = (button)view.findviewbyid(r.id.button);     button.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {               //your code here         }   }  } 

lastly remove xml:

android:onclick="onlovebuttonclicked" 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -