开发者

Problem with setOnClickListener - stopped application unexpectedly

开发者 https://www.devze.com 2023-02-24 20:46 出处:网络
I am fighting whole day with error \"The applicationhas stopped unexpectedly. Please try again.\" This problem is caused by method \"setOnClickListener\". I am working with this component following wa

I am fighting whole day with error "The application has stopped unexpectedly. Please try again." This problem is caused by method "setOnClickListener". I am working with this component following way:

public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button nnumb1 = ((Button)this.findViewById(R.id.numb1)); 
        nnumb1.setOnClickListener((OnClickListener) this);

        Button nnumb2 = ((Button)this.findViewById(R.id.numb2)); 
        nnumb2.setOnClickListener((OnClickListener) this);

    }

    public void onClickHandler(View v){
        setTitle("???");
        String pressed = null;

        switch (v.getId()) {
            case R.id.nnumb1: 
                pressed="number one";
             break;
            case R.id.nnumb2:
                pressed="number two";
             break;
         }

        new AlertDialog.Builder(this).setTitle("Info").setMessage(pressed).setNeutralButton("Okey", null).show();       
        }
}

ID of button in main.xml are called "开发者_运维百科numb1" and "numb2". It looks the problem is one the first 5 lines -- but I don't know, how to solve it... I will be glad for any hints...

Thanks!


The problem seems to be this line:

nnumb2.setOnClickListener((OnClickListener) this);

You're casting you're current Activity to a OnClickListener, but you didn't implement the correct interface, so this while give you an exception in runtime. You have to implement the OnClickListener in your Activity:

public class main extends Activity implements OnClickListener

Then you can use it like this:

numb2.setOnClickListener(this);


You may just want to setup an onClickListener for each individual button, that's typically how I handle these situations anyway.

Button nnumb1 = ((Button)this.findViewById(R.id.numb1));
nnumb1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //stuff to do if button1 is clicked
            }
        });
Button nnumb2 = ((Button)this.findViewById(R.id.numb2));
nnumb2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //stuff to do if button2 is clicked
            }
        });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号