1

I've got very very basic problem in Java (Android) writing. Here it is, I've got code:

public void WriteValue (View sender){
   Button bt=(Button)sender;
}

WriteValue is performed, when user click button. And now I want to compare button which user clicks, with button that Id I know. Something like

 if(UserButton==ClearButton) Display.setText("0");

Thanks for help Tux:)

4

3 回答 3

2

你可以只比较 ids.-

public void WriteValue (View sender) {
    Button bt = (Button)sender;
    if(bt.getId() == R.id.clearButtonId) {
        Display.setText("0");
    }
}
于 2013-11-02T23:15:13.047 回答
0

第 1 步:让你的类实现 OnClickListener

第2步 :

// global variable
Button btOne ,bTwo;

第 3 步:

// in onCreate() method
btOne = (Button)findViewById(R.id.btOne);
btTwo = (Button)findViewById(R.id.btTwo);

btOne.setOnClickListener(this);
btTwo.setOnClickListener(this);

第 4 步:从接口实现方法

puvlic void onClick(View v)
{
if(v==btOne)
{
// do work for btone
}
if(v==btTwo)
{
// do work for btTwo
}
}
于 2013-11-02T23:19:15.193 回答
0

您不需要将Viewa 投射到Button此处。您可以简单地获取发送到函数idView单击的 (假设这是在 xml 中定义的函数或通过在 Java 中设置)。所以它可能是这样的paramonClick()listener

  public void WriteValue (View sender)
  {
       int id = sender.getId();   // get the id of the View clicked
       swith (id)                 // switch logic on that id
       { 
           case (R.id clearButtonId):  // if the clearButton was clicked do this
                Display.setText("0");
                break;
           default:
                 Display.setText("Some other String);
                break;
       }
  }

恕我直言,您也可以使用if/else而不是 a switch,但这更具可读性。这很容易让您为其他Buttons 添加更多逻辑。

还可以考虑使用 Java 命名约定。根据这段代码,我假设Display是 a TextVieworsoEditText它应该以小写字母开头(例如display)。

于 2013-11-02T23:20:26.647 回答