0

我是android编程的新手,所以如果这个问题看起来很愚蠢,请原谅。

我正在 Android 中创建一个计算器,对于用户界面,我有很多按钮(10 位数字大约 20 个,以及各种操作)。现在,一旦用户按下按钮“=”,我就会计算出一个字符串表达式。但是,如果他按下任何其他按钮,则输入会更新。假设他按“1”然后输入=1;然后他按 2 然后输入变为“12”,依此类推。所以每当按下各种按钮时我都需要调用相同的函数,但是函数的输入是不同的。我可以通过制作 n 个不同的功能来解决这个问题,每个按钮一个,但这不是很可扩展。那么我该怎么做呢?

当前的xml文件是:

<Button
    android:id="@+id/Button01"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/Button03"
    android:layout_alignBottom="@+id/Button03"
    android:layout_toRightOf="@+id/Button03"
    android:onClick="UpdateExpression_/"
    android:text="/" />

<Button
    android:id="@+id/Button02"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/Button01"
    android:layout_alignBottom="@+id/Button01"
    android:layout_toRightOf="@+id/Button01"
    android:onClick="UpdateExpression_X"
    android:text="x" />

我需要更新到 android:onClick="UpdateExpression" 并提到这个函数调用的一些输入。

谢谢你。

4

2 回答 2

1

您将需要一个中央 onClick 方法,我们将其updateExpression(View v)命名为关于您的代码的注意事项:方法名称应以小写字母开头,这是 Java 命名约定。

  android:onClick="updateExpression" 

现在实现:

public void updateExpression (View v)
{
  switch (v.getId())
  {
    case R.id.button1:
    //do stuff here
    break;
    case R.id.button2:
    //do other stuff here
    break;
  }
}

您需要的原因v.getId()是因为您正在检查按钮的 id,然后如果它是那个特定的 id 就做一些事情。这个逻辑是必需的,因为您的所有按钮都将实现相同的方法。

于 2012-12-15T00:13:29.797 回答
0

这是使用代码的实现....

在 onClick 函数中,将 与v.getId()您的每个 Android 布局 ID 进行比较,例如R.id.button1 R.id.button2等...

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

    //Here are some buttons defined in the XML layout as button1, button2, etc...
    Button button1 = (Button)findViewById(R.id.button1);        
    button1.setOnClickListener(myListener);
    Button button2 = (Button)findViewById(R.id.button2);        
    button2.setOnClickListener(myListener);
    Button button3 = (Button)findViewById(R.id.button3);        
    button3.setOnClickListener(myListener);

}

//Create an anonymous implementation of OnClickListener
private OnClickListener myListener = new OnClickListener() {
    public void onClick(View v) {
      Log.d(logtag,"onClick() called");              
      Toast.makeText(MainActivity.this, "The " + v.getId() + " button was clicked.", Toast.LENGTH_SHORT).show();

    }
};
于 2012-12-15T00:16:12.537 回答