开发者

android: button onClick(), cant tell if anything is happening

My Activity onClick() below doesn't appear to be doing anything (not seeing any string appear), yet I dont get any errors. What am I missing? Is there a way to t开发者_Python百科race the function?

package com.HelloTabWidget2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class AlbumsActivity extends Activity {

    private Button closeButton;

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.tab1);
        this.closeButton = (Button)this.findViewById(R.id.button);
        this.closeButton.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
           Toast.makeText(AlbumsActivity.this, "You clicked the button", Toast.LENGTH_SHORT).show();

          }
        });


    }
}

Thanks!


I believe the issue is with the anonymous method, I get an error when trying to use your code. Just add the impliments OnClickListenter.

If you have more than one button, you'll need to add a switch or something on v.getId().

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AlbumsActivity extends Activity implements OnClickListener {
    private Button closeButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.closeButton = (Button)this.findViewById(R.id.button);
        this.closeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
         Toast.makeText(this, "You clicked the button", Toast.LENGTH_SHORT).show();

    }
}


I would say that instead of writing the below code

...setOnClickListener(new OnClickListener() {..."

I would prefer the following ocde

"...setOnClickListener(new View.OnClickListener() {..."


You can simply use following code

Button closeButton = (Button) findViewById(R.id.button);

    closeButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Onclick works", Toast.LENGTH_LONG).show();

        }
    });

If it provides exception, go and do Project -> Clean. Things will work properly

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜