簡體   English   中英

Android編程:使用onClick調用具有不同輸入的函數

[英]Android Programming: Calling function with different input using onClick

我是android編程的新手,所以如果問題看起來很愚蠢,請原諒。

我正在Android中創建一個Calculator,對於用戶界面,我有很多按鈕(大約20個10位數字,以及各種操作)。 現在,有一個字符串表達式,一旦用戶按下按鈕“ =”,我就可以計算出它。 但是,如果他按下任何其他按鈕,則輸入將被更新。 假設他按下“ 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”並提及此函數調用的一些輸入。

謝謝。

您將需要一個中央的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的情況下進行了某些操作。 由於所有按鈕都將實現相同的方法,因此需要此邏輯。

這是使用代碼的實現。

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

    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM