Skip to content
Advertisement

Get EditText input values and display some calculation result in an TextView

I have made a very basic weighted average calculator as Android Application (in Java) and it worked fine.

The user just inputs 3 values a, b, c in three EditTexts and it calculates formula:

JavaScript

Result of this mathematical equation is displayed in a TextView, all of this in the MainActivity at the press of a button.

But after creating a new project for better UI (used Android Studio template Navigation Drawer Activity) I realized that my code is not working.

How could i modify that calculator to get input in my fragment (named CalculatorWeightedFragment) to make calculations and display the result in a TextView in the same fragment when my button is pressed?

At this point all I’m getting is the display of something static and no action assigned to the button.

The code is below:

CalculatorWeightedFragment.java

JavaScript

CalculatorWeightedViewModel.java

JavaScript

Advertisement

Answer

Base on your xml layout content:

JavaScript

Example #1 (without LiveData and ViewModel)

I create some new simple fragment (as example)

JavaScript

Example #2 (with LiveData and ViewModel)

When you are using LiveData and ViewModel, you no need button in your Fragment. You can observe all of the changes.

Activity where you are creating this fragment. To have ViewModel in Fragment, you can use dependency injection (e.g. using Dagger library) or get it from ViewModelProviders (or AndroidViewModelFactory).

Here, to make example as simple as possible, I’m passing it via constructor.

Activity

JavaScript

ViewModel

You can store you values (a, b, c) as fieldsfor different purpose. Here, I’m recalculating result live, without any extra fiels. To make it as simple as possible.

JavaScript

Fragment:

Additionaly you can create separate listeners (for each of the fields). Here, I’m using one (named TextWatcher listener) for all of the fields.

JavaScript

It should works like there:

Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement