Reputation: 19
I'm trying to implement onclicklistener but it isn't working on my phone or emulator.
here is the code:
package com.slaps.guess;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
Button one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.tvd);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
tv.setText("Anything");
break;
}
}
}
the text view is not changing to anything it is still.
note: button1 exists, and their is nothing wrong with my xml. i want to implement because i have alot of button.
Upvotes: 0
Views: 3985
Reputation: 10829
You are missing one.setOnClickListener(this) in your code.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this);
tv = (TextView) findViewById(R.id.tvd);
}
Upvotes: 4
Reputation: 32748
It looks like you're missing the required XML attribute in res/layout/activity_main.xml
. Ensure it looks like:
<Button
android:id="@+id/button1"
onClick="onClick"
/>
The key being you have supplied the onClick
attribute with the name of your method to invoke.
But if you want to set the click listener programmatically than you will need to use the Button.setOnClickListener
method. If you do this your method signature will need to change to:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
Upvotes: 0
Reputation: 18112
Before using listener you will have to add it in the object for which you want it.
I guess you want for the Button one
here.
Use one.setOnClickListener(this)
after one = (Button) findViewById(R.id.button1);
Upvotes: 0