user1946705
user1946705

Reputation: 2888

How to get the value of pressed button?

I am searching the solution, how to get the value of the button which is pressed.

When I try something like this:

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

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

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

    switch (v.getId()) {
        case R.id.numb1: 
            pressed=numb1.getText().toString();
            break;
            //OR
        case R.id.numb1: 
            pressed=R.id.numb1.getText().toString();
            break;  
     }

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

Both cases in switch are unfortunately bad.

And I still can't get the value of the pressed button... Can you help me please with this problem yet?

Thank you.

Upvotes: 2

Views: 16363

Answers (4)

Leonid Maslov
Leonid Maslov

Reputation: 231

Well guys, I am pretty new in this area, but I solved this problem like that:

public void onClick(View view) {
      int intID = view.getId();
      Button button = (Button) findViewById(intID);
      String message = button.getText().toString();
}

Upvotes: 4

MByD
MByD

Reputation: 137322

pressed=((Button)v).getText(); should do the job.

Also, let your activity implement View.OnClickListener and instead of onClickHandler() override the method public void onClickHandler(View v) with your implementation.

Upvotes: 3

Thane Anthem
Thane Anthem

Reputation: 4093

Looking at your code, is it possible you have two variables with the same name but different scopes causing you confusion?

In onCreate, you declare Button numb1, but onClickHandler appears to expect numb1 to have also been declared outside of onCreate. So, should onCreate just assign a value to numb1, instead of also declaring it?

At any rate, if you were to post a more complete code example, it may help others to identify the problem, instead of just guessing about how things are.

Upvotes: 0

The Lazy Coder
The Lazy Coder

Reputation: 11828

try this.

Button sender = (Button)v;
sender.text;

Upvotes: 0

Related Questions