Reputation: 5748
I have a button in android which i have defined in fragment_main.xml as -
<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 is as 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 as there is a onClick event defined i wanted to define in a separate class file as 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 but at run time throws the error
"could not find the event listener named onLoveButtonClicked"
This however is working fine if i write the function in my MainActivity.java
Any ideas?
Thanks
Upvotes: 0
Views: 967
Reputation: 8661
Use an anonymous inner class in your 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 this from your xml:
android:onClick="onLoveButtonClicked"
Upvotes: 1
Reputation: 2053
Hello the Button is in your fragment_main.xml file
and you are setting content view in activity_main to AndroidLove activity.
i think you need to write onLoveButtonClicked() method inside Fragment not in activity.
Method name from xml and java file must same. activity/fragment that set that xml file as content view it must be have same name method with view as params.
Thanx.
Upvotes: 0