Implementing Multimeter in PSLab Android App

The Pocket Science Lab Android app being on the verge of development have various new features adding up per day. One of the new things added up recently is the splitting of the control section in three different instruments and implementing the control read section into a multimeter. This blog will be discussing about how the multimeter is implemented. The different instruments are power section, multimeter and wave generator. While in the previous implementation of control section it was divided into three parts namely control main, control read and control advanced as shown in figure (1). The control is the power source, read is the multimeter and advanced section is the wave generator. Figure  (1): Screenshot of control section Figure (1) shows the previous implementation of a multimeter i.e the read section but as we know this is way different than the actual implementation of a multimeter and thus from here comes the task of implementing a new multimeter. What is a Multimeter, how does it looks? A multimeter basically is an instrument designed to measure electric current, voltage, and usually resistance, typically over several ranges of value.           Figure (2): Showing a real multimeter instrument and its different sections [2] Figure(2) clearly shows how an actual multimeter looks. It basically has three important components i.e the display the buttons and the rotary knob or the dial and thus the task was to implement the same in PSLab android. Implementation in PSLab Figure (3) :  Screenshot of new implementation of multimeter The implementation of multimeter is thus inspired from its original look i.e it has got basic buttons, a rotary knob and a display. Figure (3) shows the implementation of multimeter in the android-app Back-end of Multimeter A separate multimeter activity was implemented for the multimeter. The main back-end part of getting the resistance, capacitance, frequency and count pulse were taken from the communication related classes such as the ScienceLab class and PacketHandler class. For example to get the voltage calculation we use the getRawableVoltage function private double getRawAverageVoltage(String channelName) { try { int chosa = this.calcCHOSA(channelName); mPacketHandler.sendByte(mCommandsProto.ADC); mPacketHandler.sendByte(mCommandsProto.GET_VOLTAGE_SUMMED); mPacketHandler.sendByte(chosa); int vSum = mPacketHandler.getVoltageSummation(); mPacketHandler.getAcknowledgement(); return vSum / 16.0; } catch (IOException | NullPointerException e) { e.printStackTrace(); Log.e(TAG, "Error in getRawAverageVoltage"); } return 0; } The above function shows the pure backend of PSLab and how data is taken from the hardware using the packet handler class, after which the data is processed in various other functions after we getting the final result. Similarly the function to get count pulse is public int readPulseCount() { try { mPacketHandler.sendByte(mCommandsProto.COMMON); mPacketHandler.sendByte(mCommandsProto.FETCH_COUNT); int count = mPacketHandler.getVoltageSummation(); mPacketHandler.getAcknowledgement(); return 10 * count; } catch (IOException e) { e.printStackTrace(); } return -1; } As we see that the data is being taken through a similar manner in the above function i.e using the packetHandler class(by sending and receiving bytes). Thus in all the other functions for capacitance, frequency similar communication model can be found. Similarly all the functions are implemented in the ScienceLab class and thus…

Continue ReadingImplementing Multimeter in PSLab Android App

Implementing Settings for Lux Meter Instrument in PSLab Android App

In PSLab android app, we have included sensor instruments which use either inbuilt sensor of smartphone or external sensor to record sensor data. For example, Lux Meter uses the light sensor to record lux data but the problem is that these instruments doesn’t contain settings option to configure the sensor record-setting like which sensor to use, change the update period etc. Therefore, we need to create a settings page for the Lux Meter instrument which allows the user to modify the properties of the sensor instrument. For that I will use Android Preference APIs to build a settings interface that is similar to setting activity in any other android app. The main building block of the settings activity is the Preference object. Each preference appears as a single setting item in an activity and it corresponds to key-value pair which stores the settings in default Shared Preferences file. Every time any setting is changed by the user the Android will store the updated value of the setting in the default shared preferences which we can read in any other activity across the app. In the following steps I will describe instruction on how to create the setting interface in Android app:  Step1 Include the dependency First, we need to include the dependency for v7 Preference Support Library by including the following code: dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.android.support:preference-v7:23.1.1' }  Step 2 Creating the preferences screen in XML For this step, I have created a preference screen which will be inflated when the settings fragment is being created. I created a file named  “lux_meter_settings.xml” and place it in the res/xml/ directory. The root node for the XML file must be a <PreferenceScreen> element. We have to add each Preference within this element. Each child I added within the <PreferenceScreen> element appears as a single item in the list of settings. The preference which I have used are: <EdittextPreference> This preference opens up a dialog box with edit text and stores whatever value is written by the user in the edit text. I have used this preference for inputting update period and high limit of data during recording. <CheckboxPreference> shows an item with a checkbox for a setting that is either enabled or disabled. The saved value is a boolean (true if it's checked). I have used this preference for enabling or disabling location data with the recorded data. <ListPreference> opens a dialog with a list of radio buttons. The saved value can be any one of the supported value types. I have used this preference to allow the user to choose between multiple sensor types. <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <EditTextPreference android:key="setting_lux_update_period" android:title="@string/update_period" android:dialogTitle="@string/update_period" android:defaultValue="1000" android:dialogMessage="Please provide time interval(in ms) at which data will be updated" android:summary="Update period is 900ms"/> <EditTextPreference android:key="setting_lux_high_limit" android:title="High Limit" android:dialogTitle="High Limit" android:defaultValue="2000" android:dialogMessage="Please provide maximum limit of LUX value to be recorded" android:summary="High Limit is 2000 Lux"/> <CheckBoxPreference android:defaultValue="false" android:key="include_location_sensor_data" android:summary="Include the location data in the logged file" android:title="Include Location…

Continue ReadingImplementing Settings for Lux Meter Instrument in PSLab Android App

Implementing Rotary Knob in PSLab Android App

PSLab android application as we all know has got various instrument such as oscilloscope, logic analyzer, wave generator, etc.. . Although many of  these instrument require redesigning of it’s UI. One such instrument is the  Multimeter. The Multimeter UI required the implementation of the rotary knob as it is also present in an actual Multimeter.Thus this blog is solely on how to implement a Rotary Knob in an Android App. Figure 1: Showing a basic knob What is Rotary Knob ? A Rotary knob is  a customizable selector that replicates the behaviour of a knob with discrete values.The knob is a powerful tool it has a lot of advantages over other radio-buttons, seek bars or other selectors.[1][2] It has an immediate graphical indication of the current value, the number of choices and where the value is in the overall range. Works fine also with few choices, as a multi-state toggle. Swipe gestures allow to change values very quickly, using the entire screen for the gesture, but only a tiny zone of it for the graphics. Implementation of Rotary Knob in your app[1] In this blog the rotary knob is implemented using the BeppiMenozzi Knob library[1] as by doing this we don’t have to manually create the extra class for the knob and we don’t have to write the code from scratch. This blog will give you step by step guide on how to implement this on your app. In your project level build.gradle file add the following lines of code. allprojects { repositories { …. maven { url "https://jitpack.io" } …. } } In you app level build.gradle file add the following lines of codes in your dependencies. compile 'com.github.BeppiMenozzi:Knob:1.9. Minimal code :- This contains the minimum number of lines of code for knob xmlns:app="http://schemas.android.com/apk/res-auto" ... <it.beppi.knoblibrary.Knob android:layout_width="64dp" android:layout_height="64dp" android:id="@+id/knob" app:kNumberOfStates="6" /> Java listener- xmlns:app="http://schemas.android.com/apk/res-auto" Knob knob = (Knob) findViewById(R.id.knob); knob.setState(firstState); knob.setOnStateChanged(new Knob.OnStateChanged() { @Override public void onState(int state) { // do something } }); This java method gives the user the position of the tip of theknob. Also there are various other advantages of using this library. The Knob is completely customizable. The many customizable attributes can all be set both via xml file, and programmatically. This  page gives the list of all the methods for customizing a knob.    Implementing a simple knob app tv= (TextView)findViewById(R.id.tv); Knob knob = (Knob) findViewById(R.id.knob); knob.setState(0); knob.setOnStateChanged(new Knob.OnStateChanged() { @Override public void onState(int state) { // do something tv.setText(String.valueOf(state)); } }); Now let us see the implementation of this simple app Figure 2: showing basic knob implementation in android So this is how we can implement a rotary knob in any Android Application. Resources: BeppiMenozzi,knob-library,github.com https://github.com/BeppiMenozzi/Knob Control knob, wikipedia.com https://en.wikipedia.org/wiki/Control_knob      

Continue ReadingImplementing Rotary Knob in PSLab Android App

Producing Waveforms using Wave Generator module in the PSLab Android App

This blog will demonstrate how to produce different waveforms using the Wave Generator module in the PSLab android app and view them on the Oscilloscope. The Wave Generator in PSLab android app is simple to use and has a UI which is similar to physical commodity wave generators. It is capable of producing different waveforms like sine, sawtooth and square wave. Apparatus Required Before getting started with the wave generator we require the following items: PSLab device An android phone with PSLab app installed in it. USB cable (Mini B) OTG(On the Go) wire Some connecting wires having pins at both ends Understanding the Wave Generator Pins Let me briefly explain the use of the pins that are going to be used in the Wave generator module: S1 and S2 pins The PSLab device contains two pins (S1, S2) which are capable of producing two independent analog waveforms (sine,  sawtooth) having different frequencies and phase offset. The frequency range is from 10Hz to 5Khz. SQR1, SQR2, SQR3 and SQR4 pin The SQR1 pin is used for producing the square waveform and all the SQ pins can be used together to produce four different PWM signal having the same frequency. These PWM signal can have a different duty cycle and phase. CH1, CH2 and CH3 pin The CH pins are used by the oscilloscope in the  PSLab android app to monitor waveform signals produced by the wave generator pins. They can be used together to simultaneously monitor multiple waveforms. Setting up the Device We need to connect the PSLab device with the mobile phone as shown in Figure 2 which can be done by following steps: Connect a micro USB(Mini B) to the PSLab device. Connect the other end of the micro USB cable to the OTG. Connect the OTG to the phone. Producing Waveforms Now, once the device has been properly connected to the device (which is shown at the top right corner of the app), then in the instruments page scroll down to the Wave Generator card and click on it to open the WaveGenerator activity. Here you will see a screen like shown in Figure 4 containing two monitors and a controlling panel with lots of buttons. Here the Waveform panel is used to control the S1 and S2 pins whose properties are shown on the left monitor screen and the Digital panel is used to control the SQR pins whose properties are shown on the right monitor screen. For sine/sawtooth wave: Connect the S1 pin to the CH1 pin using a connecting wire, then in the Waveform panel select the Wave1 button, choose the type of waveform(either sine or sawtooth), then click on the Freq button to change the frequency of the wave, then use the Seek bar or the up/down arrow buttons to change the value of frequency and then press the set button to set the frequency for the S1 pin as shown below: Now, click the view button at bottom right corner, this will directly…

Continue ReadingProducing Waveforms using Wave Generator module in the PSLab Android App

Making Zoom View in PSLab Android app

This blog demonstrates how to make a zoom view in an Android app by taking example from one made in PSLab Android app. It will mainly reflect the work done under PR #1117 in PSLab Android repository. The demonstration shown in this blog is for zooming a complete layout. But individual components of a layout can also be given this zoom effect. How to make a zoom view? Below is a step by step guide on how to implement a zoom view in an Android app : First make a  Zoom Layout class in Android Project which will further include GestureDetector, MotionEvent, etc. Now extend the Zoom Layout class from a base layout provided by Android i.e. Relative Layout, Linear Layout, etc. as per need because we need to give zoom effect to a complete layout. In this demonstration, I will use the Relative Layout class as my base class. Also to detect the gestures made by a user, we need to implement the ScaleGestureDetector.OnScaleGestureListener class. So, finally, the class implementation will look like this public class ZoomLayout extends RelativeLayout implements ScaleGestureDetector.OnScaleGestureListener { } Now make default constructors and declare variables to define the range of the minimum and maximum possible zoom, coordinates before drag, coordinates after drag, etc. private static final float MIN_ZOOM = 1.0f; private static final float MAX_ZOOM = 4.0f; private Mode mode = Mode.NONE; private float scale = 1.0f; private float lastScaleFactor = 0f; private float startX = 0f; private float startY = 0f; private float dx = 0f; private float dy = 0f; private float prevDx = 0f; private float prevDy = 0f; public ZoomLayout(Context context) { super(context); init(context); } Here startX and startY are the initial coordinates of the layout, dx and dy are the new coordinates of the layout and prevDx and prevDy are the coordinates of the previous location of the layout. Also, mode is the current mode of the gesture which will be further elaborated upon in coming steps, and all other remaining variables are for scaling the screen on gesture movements. Also, init(context) is a method which will be explained in step 5. Now, we will make a method named init() to initiate the process of scaling the layout on gesture detection. public void init(Context context) { final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this); this.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (scale > MIN_ZOOM) { mode = Mode.DRAG; startX = motionEvent.getX() - prevDx; startY = motionEvent.getY() - prevDy; } break; case MotionEvent.ACTION_MOVE: if (mode == Mode.DRAG) { dx = motionEvent.getX() - startX; dy = motionEvent.getY() - startY; } break; case MotionEvent.ACTION_POINTER_DOWN: mode = Mode.ZOOM; break; case MotionEvent.ACTION_POINTER_UP: mode = Mode.DRAG; break; case MotionEvent.ACTION_UP: mode = Mode.NONE; prevDx = dx; prevDy = dy; break; default: mode = Mode.NONE; prevDx = dx; prevDy = dy; break; } scaleDetector.onTouchEvent(motionEvent); if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) { getParent().requestDisallowInterceptTouchEvent(true); float maxDx = (child().getWidth() - (child().getWidth() / scale))…

Continue ReadingMaking Zoom View in PSLab Android app

Stepper Motors Experiment with PSLab

PSLab device is capable of building up a complete science lab almost anywhere. While the privilege is mostly taken by high school students and teachers to perform scientific experiments, electronic hobbyists can greatly be influenced from the device. One of the usages is to test and debug sensors and other electronic components before actually using them in their projects. This blog will explain how steppers motors can be used with PSLab. A stepper motor is an electromechanical device which converts electrical power into mechanical power. Also it is a brushless, synchronous electric motor that can divide a full rotation into an expansive number of steps. The stepper motor uses the theory of operation for magnets to make the motor shaft turn a precise distance when a pulse of electricity is provided. Stepper motors are similar to switched reluctance motors. [1] Figure 1: Showing the working of a stepper motor [4]                                                       Figure 1 shows the animation of a simplified stepper motor. Unlike a brushless DC motor which rotates continuously when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles as shown in the above figure. How Stepper Motors Work? Stepper Motor works on the principle of electromagnetism. Stepper motors consist of a permanent magnetic rotating shaft, called the     rotor, and electromagnets on the stationary portion that surrounds     the motor, called the stator. Figure 1 illustrates one complete rotation of a stepper motor. At position 1, we can see that the rotor is beginning at the upper     electromagnet, which is currently active (has voltage applied to it). To move the rotor clockwise (CW), the upper electromagnet is deactivated and the right electromagnet is activated, causing the rotor to move 90 degrees CW, aligning itself with the active magnet. This process is repeated in the same manner at the south and west     electromagnets until we once again reach the starting position.            Figure  (2): Showing different stages of stepper motors’ working cycle [3] What are the most common reasons to choose stepper motors over other types? [2] Positioning     – Since steppers move in precise repeatable steps, they excel in applications requiring precise positioning such as 3D printers, CNC, Camera platforms and X,Y Plotters. Some disk drives also use stepper motors to position the read/write head. Speed Control – Precise increments of movement also allow for excellent control of rotational speed for process automation and robotics. Low Speed Torque - Normal DC motors don't have very much torque at low speeds. A Stepper motor has maximum torque at low     speeds, so they are a good choice for applications requiring low speed with high precision. Applications of Stepper Motors [2] Industrial Machines – Stepper motors are used in automotive gauges and machine tooling automated production equipments. Office Equipments – Stepper motors are incorporated inside PC based scanning equipment, data storage tape drives, optical disk drive head driving mechanism, printers, bar-code printers, scanners Medical – Stepper motors are used inside medical scanners, samplers,…

Continue ReadingStepper Motors Experiment with PSLab

Working with Logic Analyzer in PSLab Android app

This blog demonstrates the working of Logic Analyzer instrument available in PSLab Android app. It also includes a detailed description of the features available in the Logic Analyzer instrument along with a step by step guide on how to work with it which will be beneficial to first-time users of the PSLab application. The functionality of the Logic Analyzer available in PSLab Android app is same as that in PSLab Desktop App. So, it would be easy for a user of PSLab Desktop Application to get acquainted with this Logic Analyzer. The only difference in this instrument is the changed and attractive UI which makes working with it very easy. Why use Logic Analyzer? The Logic Analyzer instrument provides the functionality of capturing and plotting the digital waves on the screen so that it would be easy for a user to determine the time relationship between different waves. So, this instrument would be very useful while working with timing diagrams, protocol decodes, state machines traces, assembly language, or with source-level software. How to generate different digital pulses in the PSLab app? Logic Analyzer needs to be provided with some input of digital pulses among whom time relationship is to be found out. Digital pulses generated from different systems can be directly provided as input to the Logic Analyzer for analyzing. But PSLab provides a functionality to generate digital pulses up to some constrained frequency. Following are the steps to generate different digital waves in PSLab Android application : Open PSLab Android application and click on the Wave Generator tile as shown in figure 1. After opening the instrument, the screen will look as shown in figure 2. Figure 1. Wave Generator instrument tile available in PSLab Android app Figure 2. The main screen of the Wave Generator instrument Click on the MODE button to change the mode to PWM. The screen will look as shown in figure 3. Figure 3. PWM mode in Wave Generator PSLab device provides generation of maximum four digital waves at once. In this example, I will proceed by utilizing only two pins i.e. SQR1and SQR2 (where SQR = Acronym of square wave generator and the number next to it is the pin ID available on the PSLab device) to demonstrate the working of Two Channel Mode in Logic Analyzer. Set the duty cycles and frequency for the selected pins as desired (try to keep all the duty cycles different from each other to understand the process of measurement easily). NOTE: User can also set phase angle for different waves but I will proceed with defaults. How to analyze the generated waves in Logic Analyzer? Now go back and select the Logic Analyzer tile as shown in figure 4 from the list of available instruments. A screen as shown in figure 5 should open. Figure 4. Tile of Logic Analyzer instrument available in the PSLab app Figure 5. The main screen of the Logic Analyzer instrument On the right-hand side, you can see a slider whose…

Continue ReadingWorking with Logic Analyzer in PSLab Android app

Implementing the discrete Seekbar for Wave Generator

The Wave Generator instrument in PSLab Android app allows us to produce waveforms having different values of properties like frequency, duty, phase etc. The range of these properties allowed by PSLab Device are : Table showing the range of properties that can be set for waves by PSLab device Wave Property Range Min Max Step Size Frequency 10 Hz 5000 Hz 1 Hz Phase 0° 360° 1° Duty 10% 100% 10% We can set these values using the up/down arrow buttons provided by the wave generator but the problem is that the range of values is very high and least counts are small so it is convenient to set the values using only the up and down arrow buttons. Therefore we need something that could allow us to directly set any value of our choice while keeping the UI interactive. The solution to this problem - “Discrete Seekbar”. It contains a slider having points at equal intervals and whose length represents the range of the values and a head that slides over the slider and is used to select a specific value from a range of values. I have included the discrete Seekbar in Wave Generator by using a third-party library if you want to add Seekbar directly you can do that by directly using the default Seekbar widget provided by Android SDK and setting the following attribute in as shown below. android:theme = “@style/Widget.AppCompat.SeekBar.Discrete” Refer to this post[2] for implementing Seekbar directly without an external library. The reason I chose this library is that:- It offers various implementation of different types of Seekbar like discrete and continuous. Implementation of Seekbar is simpler and it offers various customizations like thumb color, track color, tick text etc.   In following steps I will implement the discrete Seekbar: Step 1 Adding the dependency For this project, I will be using an external library “IndicatorSeekbarLibrary” by Warkiz[1], for adding the dependency we need to include the following code in our build.gradle file. dependencies{ implementation 'com.github.warkiz.widget:indicatorseekbar:2.0.9' } Step 2 Including the Seekbar in layout For this step, we need to add the Seekbar widget using <com.warkiz.widget.IndicatorSeekBar> XML tag in our wave generator layout file to include the Seekbar in our layout as shown in the code below: <com.warkiz.widget.IndicatorSeekBar android:layout_width="match_parent" android:layout_height="wrap_content" app:isb_max="5000" app:isb_min="0" app:isb_ticks_count="5" app:isb_thumb_color="@color/color_green" app:isb_thumb_size="20dp" app:isb_track_background_color="@color/color_gray" app:isb_track_background_size="2dp" app:isb_track_progress_color="@color/color_blue" app:isb_track_progress_size="4dp" /> Some important attributes used above: app:isb_max : defines the max value that can be achieved by the Seekbar. app:isb_min :  defines the min value that can be achieved by the Seekbar app:isb_ticks_count: no. of ticks(interval) that has to be shown on the slider We can see different components of Seekbar like track, indicator, thumb, tick of SeekBar in the following diagram[2]. Step 3 Attaching the listener to the Seekbar in Java file In this step we need to attach the listener to the Seekbar to record changes in the Seekbar made by the user, for this we will create a new listener with the help of onSeekBarChangeListener interface and attach it with the Seekbar as shown in following code…

Continue ReadingImplementing the discrete Seekbar for Wave Generator

Implementing Carousel Slider in PSLab Android App

This blog is a demonstration for creating a Carousel Picker in Android by taking an example of the Carousel Picker made in PSLab Android app under PR #1007. Some improvement to this would be to add custom animation to the ViewPager and adjusting the ViewPager sliding speed. So first let’s start with the basics and terminology of Carousel. What is Carousel? Carousel according to the dictionary means roundabout or merry-go-round. The term was mainly used for the traditional amusement ride of a merry-go-round in amusement parks with seats of horses. The same is the working of Carousel View in Android. It gives a smooth sliding effect to slide between a variety of options available. How to implement Carousel View in the app? Following are the steps to implement a basic Carousel View in the app. Further effects and upgrades can be given as per the need. The first step is to add jitpack to your app’s gradle file maven { url 'https://jitpack.io '} Now add a library dependency in your project level gradle file compile 'com.github.Vatican-Cameos:CarouselPicker:v1.0 The above dependency uses the View Pager and Gesture Detector functionality provided by Android. The Gesture Detector class detects the swipe gesture made by the user and the View Pager highlights the relevant label in the Carousel box according to the swipe done i.e left or right. Now Carousel Picker is ready to be added directly to layouts. So, add the Carousel by adding the following layout code at a proper section in layouts file. <in.goodiebag.carouselpicker.CarouselPicker android:id="@+id/carouselPicker" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:background="#DDD" apps:items_visible="three" /> Here, the items_visible is used to provide the Carousel Picker with the number of max items to be seen at a time on screen where only one item will be in focus. Other items are adjusted on the side and can be viewed by scrolling. Now as we have implemented the layouts, so now’s the time to set adapter and resource type for Carousel to hold in Java files. First, find the Carousel View with its id. CarouselPicker carouselPicker = findViewById(R.id.carouselPicker); Now set a list of items to be added in the Carousel Picker. The items can be both images and texts. List<CarouselPicker.PickerItem> items = new ArrayList<>(); To add images : items.add(new CarouselPicker.DrawableItem(R.mipmap.ic_launcher)); To add texts/strings : items.add(new CarouselPicker.TextItem("Example", 10)); Here, the integer that is added after the text indicates the size in sp of the text that is to be displayed in Carousel View. Now after creating a list of items, make an adapter which provides this list of information to Carousel Picker. CarouselPicker.CarouselViewAdpater adapter = new CarouselPicker.CarouselViewAdpater(this, items); Now set the adapter for the Carousel View : carouselPicker.setAdapter(adapter); To dynamically add items to the Carousel View, simply change the list of items in the list provided to the adapter and then use adapter.notifyDataSetChanged(); Now to change the functionality of the app with every Carousel item, implement the onPageChangeListener as Carousel View implements ViewPager class. carouselPicker.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }…

Continue ReadingImplementing Carousel Slider in PSLab Android App

Making Bottomsheet responsive using Custom Gesture Detector in PSLab Android App

In the previous blog Creating Instruction Guide using Bottomsheet, I have created the Bottom Sheet guide in instrument activities in PSLab Android app. But simply adding the Bottom Sheet in the layout is not enough as it could lead to some UI issues like no proper way to show or hide the Bottom Sheet, therefore, he/she will find it difficult to work with Bottom Sheet that could degrade User Experience. We need to make the Bottom Sheet responsive and interactive which we can do by capturing swipe gestures done by the user and overriding their functionality i.e. when the user slides up with the finger then the Bottom Sheet will reveal itself and when the user slides the finger down the Bottom Sheet will hide. For this Android provides a class GestureDetector which is used with another class SimpleOnGestureListener which acts as a listener to capture Gesture events like swipe, pinch, scroll, long press etc. In this blog, I will create a custom gesture listener that will listen to the swipe events and according to the gestures it will show/hide the Bottom Sheet. I will start by creating a gesture listener class called “SwipeGestureListener” extending the class ‘GestureDetector.SimpleOnGestureListener’ and also as I need swipe gestures to control the Bottom Sheet, so I will pass the reference of the Bottom Sheet as a parameter in the constructor. public class SwipeGestureListener extends GestureDetector.SimpleOnGestureListener{ private BottomSheetBehavior bottomSheet; public SwipeGestureDetector(BottomSheetBehavior bt) { bottomSheet = bt; } } Now in this listener class as we are concerned with the swipe events so will only override the below method provided by ‘GestureDetector.SimpleOnGestureListener’ interface public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) This method is called whenever the user swipes its finger in any direction. In the above code, we can see that the method provides with object e1 and e2 of type MotionEvent. The MotionEvent class is used to report movements in terms of Action Codes like ACTION_DOWN, ACTION_UP and also contains other information about the touch like the pressure of the touch, x and y coordinate, orientation of the contact area etc.  The e1 object will have the attribute values relating to the point when the swipe started and the e2 object will have attribute values relating to the point when the swipe has ended. Now, the main thing we need to determine if the direction of the swipe which is not directly available using the MotionEvent object. So, to determine the direction of the swipe I will fetch the coordinates of the initial point and terminal point of the swipe using the objects initial and final point i.e., e1 and e2. //Initial Point float x1 = e1.getX(), y1 = e1.getY(); //Final Point float x2 = e2.getX(), y2 = e2.getY(); Then, using these coordinates to calculate the angle of the swipe and based on the angle I will return the direction of the swipe as shown in the code below private Direction getDirection(float x1, float y1, float x2, float y2) { Double angle = Math.toDegrees(Math.atan2(y1 - y2,…

Continue ReadingMaking Bottomsheet responsive using Custom Gesture Detector in PSLab Android App