简体   繁体   中英

implementing onclicklistener is not working?

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.

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);     
}

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);

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   
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM