I am new to android programming and so please pardon if the question looks stupid.
I am creating a Calculator in Android and for the user interface I have many buttons (around 20 for 10 digits, and various operation). Now there is a string expression that I calculate once the user presses the button “=”. However if he presses any other button then the input is updated. Say he presses “1” then input =1; then he presses 2 then input becomes “12” and so on.
So I need to call the same function whenever various buttons are pressed, but the input to the function is different.
I can go-by this by making n different functions, one for each button but that is not very scalable.
So how can I go about it?
The current xml file is:
<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" />
I need to update to android:onClick=”UpdateExpression” and mention some input to this function call.
Thank you.
You will need a central onClick method, let’s call it
updateExpression(View v)Also a note about your code: method names should start with a lowercase letter, it’s a Java naming convention.Now the implementation:
The reason you need
v.getId()is because you’re checking the id of the button then doing something if it’s that particular id. This logic is needed since all your buttons will implement that same method.