开发者

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开发者_JS百科.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.


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


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.


try this.

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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜