How to design dynamic UI elements in Android

1k views Asked by At

I have a general question about how to design dynamic UI elements in Android (with Java).

I would like to have a thermometer in my app that depending on some external information increases or decreases a red bar(shown below). enter image description here. How can i design something like this in Android?

I could for example just design the thermometer without the red bar as a jpeg with some drawing program and then somehow implement the red bar in Android as an object that can be changed programmatically whereas the 'rim' of the thermometer does not change. The problem I see with this approach is that I believe it is extremely difficult to match the rim of the thermometer with the red bar for different screen sizes and resolutions. Do you have another suggestion on how I could do something like this? Is there maybe a library for this?

I'd appreciate every comment as I have no experience whatsoever generally with designing such dynamic UI objects.

2

There are 2 answers

44
Nikhil Jain On BEST ANSWER

Updated Answer:

I have created a demo project on Github here. This project has the Thermometer custom view in which the outer thermometer is drawn from an image file and the inside mercury view of the thermometer is drawn from the code. You can look over the project of user kofigyan I shared in my previous answer for other customizations.

Previous Answer:

I think what are you looking for is creating Custom Views in Android.

You can extend the Android View class and can create your Custom View. The View has a Canvas object on which you can draw the shape of a Thermo-meter and can build functionalities to change the state of your shape in your subclass itself. Moreover, with the Paint object, you can paint your drawn shape.

I found this project on Github by a user kofigyan.

2
Narendra_Nath On

For having a dynamic ui you can take two approaches.

  1. Jetpack Compose(not being discussed since it's still in Beta)
  2. LiveData and observer pattern

In LiveData and observer pattern. Give the temperature as a LiveData variable(in your ViewModel) and implement an Observer in your MainActivity which gets triggered automatically when the value of the temperature live data changes.

For getting the output graphic you can use a canvas and then draw on it and tie it to the temperature variable. You could for example use the Canvas.drawRect function to create a short or long rectangle depending on the temperature. ( the part from the circle to the top of the thermometer can be the rectangle)