开发者

Registering listener in java/android, a little question

开发者 https://www.devze.com 2023-03-12 23:38 出处:网络
I wan reading here about handling UI events. I know java pretty well but still never had the chance of writing a gui so I don\'t know much about listeners. Anyway, they use

I wan reading here about handling UI events. I know java pretty well but still never had the chance of writing a gui so I don't know much about listeners. Anyway, they use a technique I have never came across before, here's what I mean

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
  public void onClick(View v) {
    // do something when the button is clicked
  }
};

The first line of code confuses me: it looks like a declareation of a new object, but then its a method? I just don't understand this code and if you can help me understand it I 开发者_JS百科can continue my assignment :)

P.s. two more question: if I have several buttons on the screen, they all share the same onCLick() method? and if so, how do I know which one was clicked?

Thanks!


Hi you can write this way also

public class testActivity extends Activity implements OnClickListener {

And Add this way...

ImageButton Ibutton = (ImageButton) findViewById(R.id.button_1);
Ibutton.setOnClickListener(this);      

ImageButton Ibutton2 = (ImageButton) findViewById(R.id.button_2);
Ibutton2.setOnClickListener(this);      


@Override
public void onClick(View v) {
switch(v.getId()){
    case R.id.button_1:
    // action to preform on button 1
        Toast.makeText(testActivity.this, "Button 1 pressed ", Toast.LENGTH_SHORT).show();
        break;
    case R.id.button_2:
    // action to preform on button 1
        Toast.makeText(testActivity.this, "Button 2 pressed ",     Toast.LENGTH_SHORT).show();
        break;
    }
}   


As each view is attached with separate listener you each event can recognize that it belongs to which view

use the following approach

step1 your class should implement OnclickListener eg

public class A implements OnClickListener

step2 Add onclicklistener to all buttons

button1 = (Button) findViewById(R.id.btn1);
button2 = (Button) findViewById(R.id.btn2);
button3 = (Button) findViewById(R.id.btn3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);

step3 write implementation of onClickMethod

@Override
    public void onClick(View view) {
        if (view == button1) {
            //do button1 click action
        } else if (view ==button2) {

            //do button2 click action

        } else if (view == button3) {
//do button3 click action
        }
0

精彩评论

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

关注公众号