Reputation: 15
I am new in java and Android. I am working on simple project that's almost complete. But I am facing some problem in XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/a"
android:layout_width="35dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:inputType="number"
android:minWidth="60dp" />
<Button
android:id="@+id/button1"
android:layout_width="47dp"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
</LinearLayout>
When a user enters a number in edit text and press the button then text view should show this result:
"enters number minus(-)30"
Like if a user enter number 50 then result show 20 in the text box (50-30=20)
I know only basic Java and I never do math in Java before so I dont know what i write in code. Search a lot on google and stackoverflow.com and also read many books but never find that simple math.
Any help would be appreciated.
Upvotes: 0
Views: 370
Reputation: 5494
btnsub.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String edtval = edttxt.getText().toString().trim();
if(!edtval.equals("")){
int val = Integer.parseInt(edtval);
int finalval = val - 30;
textview.setText(String.valueOf(finalval));
}
}
});
Upvotes: 1
Reputation: 13525
Simple math is very simple to perform.
You first need to get a references to your Views as follows
EditText editText = (EditText) findViewById(R.id.a);
Button button = (Button) findViewById(R.id.button1);
TextView textView = (TextView) findViewById(R.id.total);
Then set an onClickListener for the Button and do the operation inside the onClick Method
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Integer input = 0;
try {
input = Integer.parseInt(editText.getText().toString());
} catch (NumberFormatException e) {
input = 0;
}
input = input - 30;
textView.setText(input.toString() + "");
}
}
Upvotes: 0
Reputation: 390
btnsub.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int num;
try {
num= Integer.parseInt(edttxt.getText().toString());
textview.setText(""+(num - 30));
} catch (NumberFormatException e) {
// Open a dialog for incorrect input,i.e., Not a number
}
}
});
Upvotes: -1
Reputation: 12733
btnsub.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String edtval = edttxt.getText().toString().trim();
if(!edtval.equals("")){
int val = Integer.parseInt(edtval);
int finalval = val - 30;
textview.setText(finalval+"");
}
}
});
Upvotes: 2