archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Detecting Common Gestures using the Android 6 Gesture Detector Class - Techotopia
    Android Studio entering CommonGestures into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of an empty activity named CommonGesturesActivity with a corresponding layout resource file named activity common gestures Click on the Finish button to initiate the project creation process Once the new project has been created navigate to the app res layout activity common gestures xml file in the Project tool window and double click on it to load it into the Designer tool Within the Designer tool double click on the Hello World TextView component and in the property popup window enter gestureStatusText as the ID Finally move the TextView so that it is positioned in the center of the display Implementing the Listener Class As previously outlined it is necessary to create a class that implements the GestureDetector OnGestureListener interface and if double tap detection is required the GestureDetector OnDoubleTapListener interface While this can be an entirely new class it is also perfectly valid to implement this within the current activity class For the purposes of this example therefore we will modify the CommonGesturesActivity class to implement these listener interfaces Edit the CommonGesturesActivity java file so that it reads as follows to declare the interfaces and to extract and store a reference to the TextView component in the user interface package com ebookfrenzy commongestures import android support v7 app AppCompatActivity import android os Bundle import android view GestureDetector import android widget TextView public class CommonGesturesActivity extends AppCompatActivity implements GestureDetector OnGestureListener GestureDetector OnDoubleTapListener private TextView gestureText Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity common gestures gestureText TextView findViewById R id gestureStatusText eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Declaring that the class implements the listener interfaces mandates that the corresponding methods also be implemented in the class package com ebookfrenzy commongestures import android support v7 app AppCompatActivity import android os Bundle import android view GestureDetector import android widget TextView import android view MotionEvent public class CommonGesturesActivity extends AppCompatActivity implements GestureDetector OnGestureListener GestureDetector OnDoubleTapListener private TextView gestureText Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity common gestures gestureText TextView findViewById R id gestureStatusText Override public boolean onDown MotionEvent event gestureText setText onDown return true Override public boolean onFling MotionEvent event1 MotionEvent event2 float velocityX float velocityY gestureText setText onFling return true Override public void onLongPress MotionEvent event gestureText setText onLongPress Override public boolean onScroll MotionEvent e1 MotionEvent e2 float distanceX float distanceY gestureText setText onScroll return true Override public void onShowPress MotionEvent event gestureText setText onShowPress Override public boolean onSingleTapUp

    Original URL path: http://www.techotopia.com/index.php/Detecting_Common_Gestures_using_the_Android_6_Gesture_Detector_Class (2016-02-13)
    Open archived version from archive


  • Implementing Custom Gesture and Pinch Recognition on Android 6 - Techotopia
    next step therefore is to create a new project Creating the Example Project Create a new project in Android Studio entering CustomGestures into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of an empty activity named CustomGesturesActivity with a corresponding layout file named activity custom gestures eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Click on the Finish button to initiate the project creation process Adding the Gestures File to the Project Within the Android Studio Project tool window locate and right click on the res folder located under app and select New Directory from the resulting menu In the New Directory dialog enter raw as the folder name and click on the OK button Using the appropriate file explorer utility for your operating system type locate the gestures file previously pulled from the SD Card and copy and paste it into the new raw folder in the Project tool window Designing the User Interface This example application calls for a very simple user interface consisting of a LinearLayout view with a GestureOverlayView layered on top of it to intercept any gestures performed by the user Locate the app res layout activity custom gestures xml file and double click on it to load it into the Designer tool By default Android Studio has provided a RelativeLayout component as the root element of the user interface layout so this will need to be deleted and replaced with a LinearLayout Switch the Designer tool to Text mode using the Text tab along the bottom edge of the panel and modify the XML for the layout so that it matches the following listing xml version 1 0 encoding utf 8 LinearLayout android orientation vertical android layout width match parent android layout height match parent xmlns android http schemas android com apk res android LinearLayout Return to Design mode locate the Expert section of the Palette and drag and drop a GestureOverlayView object onto the layout canvas Select the GestureOverlayView instance in the layout and use the Properties panel or Designer toolbar buttons to change the layout width and layout height properties to match parent so that the view fills the available space Double click on the GestureOverlayView instance and use the popup property panel to change the ID to gOverlay When completed the activity custom gestures xml file should read as follows xml version 1 0 encoding utf 8 LinearLayout android orientation vertical android layout width match parent android layout height match parent xmlns android http schemas android com apk res android android gesture GestureOverlayView android layout width match parent android layout height match parent android id id gOverlay android layout gravity center horizontal android gesture GestureOverlayView LinearLayout Loading the Gestures File Now that the gestures file has been added to the project the next step is to write some code so that the file is loaded when the activity starts up For the purposes of this project the code to achieve this will be placed in the onCreate method of the CustomGesturesActivity class located in the CustomGesturesActivity java source file as follows package com ebookfrenzy customgestures import android support v7 app AppCompatActivity import android os Bundle import android gesture GestureLibraries import android gesture GestureLibrary import android gesture GestureOverlayView import android gesture GestureOverlayView OnGesturePerformedListener public class CustomGesturesActivity extends AppCompatActivity implements OnGesturePerformedListener private GestureLibrary gLibrary Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity custom gestures gLibrary GestureLibraries fromRawResource this R raw gestures if gLibrary load finish eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters In addition to some necessary import directives the above code changes to the onCreate method also create a GestureLibrary instance named gLibrary and then loads into it the contents of the gestures file located in the raw resources folder The activity class has also been modified to implement the OnGesturePerformedListener interface which requires the implementation of the onGesturePerformed callback method which will be created in a later section of this chapter Registering the Event Listener In order for the activity to receive notification that the user has performed a gesture on the screen it is necessary to register the OnGesturePerformedListener event listener on the gLayout view a reference to which can be obtained using the findViewById method as outlined in the following code fragment Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity custom gestures gLibrary GestureLibraries fromRawResource this R raw gestures if gLibrary load finish GestureOverlayView gOverlay GestureOverlayView findViewById R id gOverlay gOverlay addOnGesturePerformedListener this Implementing the onGesturePerformed Method All that remains before an initial test run of the application can be performed is to implement the OnGesturePerformed callback method This is the method which will be called when a gesture is performed on the GestureOverlayView instance package com ebookfrenzy customgestures import android support v7 app AppCompatActivity import android os Bundle import android gesture GestureLibraries import android gesture GestureLibrary import android gesture GestureOverlayView import android gesture GestureOverlayView OnGesturePerformedListener import android gesture Prediction import android widget Toast import android gesture Gesture import java util ArrayList public class CustomGesturesActivity extends AppCompatActivity implements OnGesturePerformedListener private GestureLibrary gLibrary Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity custom gestures gLibrary GestureLibraries fromRawResource this R raw gestures if gLibrary load finish GestureOverlayView gOverlay GestureOverlayView findViewById R id gOverlay gOverlay addOnGesturePerformedListener this public void onGesturePerformed GestureOverlayView overlay Gesture gesture ArrayList Prediction

    Original URL path: http://www.techotopia.com/index.php/Implementing_Custom_Gesture_and_Pinch_Recognition_on_Android_6 (2016-02-13)
    Open archived version from archive

  • An Introduction to Android 6 Fragments - Techotopia
    element are android name which must reference the class associated with the fragment and tools layout which must reference the XML resource file containing the layout of the fragment Once added to the layout of an activity fragments may be viewed and manipulated within the Android Studio Designer tool Figure 24 1 for example shows the above layout with the embedded fragment within the Android Studio Designer Figure 24 1 Adding and Managing Fragments in Code The ease of adding a fragment to an activity via the activity s XML layout file comes at the cost of the activity not being able to remove the fragment at runtime In order to achieve full dynamic control of fragments during runtime those activities must be added via code This has the advantage that the fragments can be added removed and even made to replace one another dynamically while the application is running When using code to manage fragments the fragment itself will still consist of an XML layout file and a corresponding class The difference comes when working with the fragment within the hosting activity There is a standard sequence of steps when adding a fragment to an activity using code These steps are as follows 1 Create an instance of the fragment s class 2 Pass any additional intent arguments through to the class 3 Obtain a reference to the fragment manager instance 4 Call the beginTransaction method on the fragment manager instance This returns a fragment transaction instance 5 Call the add method of the fragment transaction instance passing through as arguments the resource id of the view that is to contain the fragment and the fragment class instance 6 Call the commit method of the fragment transaction The following code for the sake of an example adds a fragment defined by the FragmentOne class so that it appears in the container view with an id of LinearLayout1 FragmentOne firstFragment new FragmentOne firstFragment setArguments getIntent getExtras FragmentManager fragManager getSupportFragmentManager FragmentTransaction transaction fragManager beginTransaction transaction add R id LinearLayout1 firstFragment transaction commit The above code breaks down each step into a separate statement for the purposes of clarity The last four lines can however be abbreviated into a single line of code as follows getSupportFragmentManager beginTransaction add R id LinearLayout1 firstFragment commit Once added to a container a fragment may subsequently be removed via a call to the remove method of the fragment transaction instance passing through a reference to the fragment instance that is to be removed transaction remove firstFragment Similarly one fragment may be replaced with another by a call to the replace method of the fragment transaction instance This takes as arguments the id of the view containing the fragment and an instance of the new fragment The replaced fragment may also be placed on what is referred to as the back stack so that it can be quickly restored in the event that the user navigates back to it This is achieved by making a call to

    Original URL path: http://www.techotopia.com/index.php/An_Introduction_to_Android_6_Fragments (2016-02-13)
    Open archived version from archive

  • Using Fragments in Android Studio - An Example - Android 6 - Techotopia
    android com apk res android android layout width match parent android layout height match parent TextView android id id textView1 android layout width wrap content android layout height wrap content android layout centerHorizontal true android layout centerVertical true android text Fragment Two android textAppearance android attr textAppearanceLarge RelativeLayout Once the XML changes have been made switch back to Design mode select the TextView component and click on the light bulb icon followed by the I18N message to display the Extract Resource dialog Name the resource text label and click on OK to create a string resource for the button Upon completion of these steps the user interface layout for this second fragment should resemble that of Figure 25 3 Figure 25 3 As with the first fragment this one will also need to have a class associated with it Right click on app java com ebookfrenzy fragmentexample in the Project tool window From the resulting menu select the New Java Class option Name the fragment TextFragment and click OK to create the class Edit the new TextFragment java class file and modify it to implement the onCreateView method and designate the class as extending the Android Fragment class package com ebookfrenzy fragmentexample import android os Bundle import android support v4 app Fragment import android view LayoutInflater import android view View import android view ViewGroup public class TextFragment extends Fragment Override public View onCreateView LayoutInflater inflater ViewGroup container Bundle savedInstanceState View view inflater inflate R layout text fragment container false return view Now that the basic structure of the two fragments has been implemented they are ready to be embedded in the application s main activity Adding the Fragments to the Activity The main activity for the application has associated with it an XML layout file named activity fragment example xml For the purposes of this example the fragments will be added to the activity using the fragment element within this file Using the Project tool window navigate to the app res layout section of the FragmentExample project and double click on the activity fragment example xml file to load it into the Android Studio Designer tool With the Designer tool in Design mode select and delete the default TextView object from the layout and scroll down the palette until the Custom section comes into view Click on the fragment entry to display a list of Fragments available within the current project as illustrated in Figure 25 4 Figure 25 4 Select the ToolbarFragment entry from the list and click on the OK button to dismiss the Fragments dialog Move the mouse pointer to the top center edge of the parent layout area so that the centerHorizontal and alignParentTop options are displayed Figure 25 5 Figure 25 5 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Once correctly positioned release the fragment to add it to the layout Once added a message panel will appear Figure 25 6 indicating that the Designer tool needs to know which fragment to display during the preview session Display the ToolbarFragment fragment by clicking on the Use layout toolbar fragment link within the message Figure 25 6 Click on the fragment entry in the Custom section of the palette once again this time selecting the TextFragment entry from the fragment dialog before clicking on the OK button Move the mouse pointer to the center of the layout so that the centerHorizontal and centerVertical properties are activated and release the fragment When the rendering message appears click on the Use layout text fragment option Note that the fragments are now visible in the layout as demonstrated in Figure 25 7 Figure 25 7 Before proceeding to the next step double click on the TextFragment instance in the layout and within the resulting panel change the id of the fragment to text fragment Making the Toolbar Fragment Talk to the Activity When the user touches the button in the toolbar fragment the fragment class is going to need to get the text from the EditText view and the current value of the SeekBar and send them to the text fragment As outlined in An Introduction to Android 6 Fragments fragments should not communicate with each other directly instead using the activity in which they are embedded as an intermediary The first step in this process is to make sure that the toolbar fragment responds to the button being clicked We also need to implement some code to keep track of the value of the SeekBar view For the purposes of this example we will implement these listeners within the ToolbarFragment class Select the ToolbarFragment java file and modify it so that it reads as shown in the following listing package com ebookfrenzy fragmentexample import android os Bundle import android support v4 app Fragment import android view LayoutInflater import android view View import android view ViewGroup import android content Context import android widget Button import android widget EditText import android widget SeekBar import android widget SeekBar OnSeekBarChangeListener public class ToolbarFragment extends Fragment implements OnSeekBarChangeListener private static int seekvalue 10 private static EditText edittext Override public View onCreateView LayoutInflater inflater ViewGroup container Bundle savedInstanceState Inflate the layout for this fragment View view inflater inflate R layout toolbar fragment container false edittext EditText view findViewById R id editText1 final SeekBar seekbar SeekBar view findViewById R id seekBar1 seekbar setOnSeekBarChangeListener this final Button button Button view findViewById R id button1 button setOnClickListener new View OnClickListener public void onClick View v buttonClicked v return view public void buttonClicked View view Override public void onProgressChanged SeekBar seekBar int progress boolean fromUser seekvalue progress Override public void onStartTrackingTouch SeekBar arg0 Override public void onStopTrackingTouch SeekBar arg0 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99

    Original URL path: http://www.techotopia.com/index.php/Using_Fragments_in_Android_Studio_-_An_Example_-_Android_6 (2016-02-13)
    Open archived version from archive

  • Animating User Interfaces with the Android 6 Transitions Framework - Techotopia
    enter Transitions between two scenes using the default AutoTransition class can be triggered using the go method of the TransitionManager class TransitionManager go scene2 Scene instances can be created easily in code by bundling the view elements into one or more ViewGroups and then creating a scene from those groups For example Scene scene1 Scene viewGroup1 Scene scene2 Scene viewGroup2 viewGroup3 Custom Transitions and TransitionSets in Code The examples outlined so far in this chapter have used the default transition settings in which resizing fading and motion are animated using pre configured behavior These can be modified by creating custom transitions which are then referenced during the transition process Animations are categorized as either change bounds relating to changes in the position and size of a view and fade relating to the visibility or otherwise of a view A single Transition can be created as follows Transition myChangeBounds new ChangeBounds This new transition can then be used when performing a transition TransitionManager go scene2 myChangeBounds Multiple transitions may be bundled together into a TransitionSet instance The following code for example creates a new TransitionSet object consisting of both change bounds and fade transition effects TransitionSet myTransition new TransitionSet myTransition addTransition new ChangeBounds myTransition addTransition new Fade Transitions can be configured to target specific views referenced by view ID For example the following code will configure the previous fade transition to target only the view with an ID that matches myButton1 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters TransitionSet myTransition new TransitionSet myTransition addTransition new ChangeBounds Transition fade new Fade fade addTarget R id myButton1 myTransition addTransition fade Additional aspects of the transition may also be customized such as the duration of the animation The following code specifies the duration over which the animation is to be performed Transition changeBounds new ChangeBounds changeBounds setDuration 2000 As with Transition instances once a TransitionSet instance has been created it can be used in a transition via the TransitionManager class For example TransitionManager go scene1 myTransition Custom Transitions and TransitionSets in XML While custom transitions can be implemented in code it is often easier to do so via XML transition files using the fade and changeBounds tags together with some additional options The following XML includes a single changeBounds transition xml version 1 0 encoding utf 8 changeBounds As with the code based approach to working with transitions each transition entry in a resource file may be customized The XML below for example configures a duration for a change bounds transition changeBounds android duration 5000 Multiple transitions may be bundled together using the transitionSet element xml version 1 0 encoding utf 8 transitionSet xmlns android http schemas android com apk res android fade android duration 2000 android fadingMode fade out changeBounds android duration 5000 targets target android targetId id

    Original URL path: http://www.techotopia.com/index.php/Animating_User_Interfaces_with_the_Android_6_Transitions_Framework (2016-02-13)
    Open archived version from archive

  • An Android 6 Transition Tutorial using beginDelayedTransition - Techotopia
    ePub PDF Kindle editions contain 65 chapters Implementing beginDelayedTransition Animation The objective for the initial phase of this tutorial is to implement a touch handler so that when the user taps on the layout view the button view moves to the lower right hand corner of the screen and increases in size Locate the TransitionDemoActivity java file located in the Project tool window under app java com ebookfrenzy transitiondemo and modify the onCreate method to implement the onTouch handler package com ebookfrenzy transitiondemo import android support v7 app AppCompatActivity import android os Bundle import android view MotionEvent import android view View import android view ViewGroup import android widget RelativeLayout public class TransitionDemoActivity extends AppCompatActivity ViewGroup myLayout Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity transition demo myLayout ViewGroup findViewById R id myLayout myLayout setOnTouchListener new RelativeLayout OnTouchListener public boolean onTouch View v MotionEvent m handleTouch return true eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters The above code simply sets up a touch listener on the RelativeLayout container and configures it to call a method named handleTouch when a touch is detected The next task therefore is to implement the handleTouch method as follows public void handleTouch View view findViewById R id myButton1 RelativeLayout LayoutParams params new RelativeLayout LayoutParams RelativeLayout LayoutParams WRAP CONTENT RelativeLayout LayoutParams WRAP CONTENT params addRule RelativeLayout ALIGN PARENT RIGHT RelativeLayout TRUE params addRule RelativeLayout ALIGN PARENT BOTTOM RelativeLayout TRUE view setLayoutParams params ViewGroup LayoutParams lparams view getLayoutParams lparams width 500 lparams height 350 view setLayoutParams lparams This method obtains a reference to the button view in the user interface layout and creates a new set of layout parameter rules designed to move the button to the bottom right hand corner of the parent layout and to increase the button s dimensions Once created these new parameters are applied to the button Test the code so far by compiling and running the application Once launched touch the background not the button and note that the button moves and resizes as illustrated in Figure 28 1 Figure 28 1 Although the layout changes took effect they did so instantly and without any form of animation This is where the call to the beginDelayedTransition method of the TransitionManager class comes in All that is needed to add animation to this layout change is the addition of a single line of code before the layout changes are implemented Remaining within the TransitionDemoActivity java file modify the code as follows package com ebookfrenzy transitiondemo import android support v7 app AppCompatActivity import android os Bundle import android view MotionEvent import android view View import android view ViewGroup import android widget RelativeLayout import android transition TransitionManager public class TransitionDemoActivity extends AppCompatActivity public void handleTouch View view findViewById R id myButton1 TransitionManager beginDelayedTransition myLayout RelativeLayout

    Original URL path: http://www.techotopia.com/index.php/An_Android_6_Transition_Tutorial_using_beginDelayedTransition (2016-02-13)
    Open archived version from archive

  • Implementing Android 6 Scene Transitions – A Tutorial - Techotopia
    will no longer be present in the second scene For the purposes of avoiding duplicated effort the layout file for the second scene will be created by copying and modifying the scene1 layout xml file Within the Project tool window locate the app res layout scene1 layout xml file right click on it and select the Copy menu option Right click on the layout folder this time selecting the Paste menu option and change the name of the file to scene2 layout xml when prompted to do so eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Double click on the new scene2 layout xml file to load it into the Designer tool and switch to Design mode if necessary Select and delete the Three button and move the first and second buttons to the bottom right and bottom left locations as illustrated in Figure 29 3 Figure 29 3 Switch Designer to Text mode and verify that the XML matches that listed below xml version 1 0 encoding utf 8 RelativeLayout xmlns android http schemas android com apk res android android layout width match parent android layout height match parent Button android layout width wrap content android layout height wrap content android text string one string android id id button android onClick goToScene2 android layout alignParentBottom true android layout alignParentRight true android layout alignParentEnd true Button android layout width wrap content android layout height wrap content android text string two string android id id button2 android onClick goToScene1 android layout alignParentBottom true android layout alignParentLeft true android layout alignParentStart true RelativeLayout Entering the First Scene If the application were to be run now only the blank layout represented by the activity scene transitions xml file would be displayed Some code must therefore be added to the onCreate method located in the SceneTransitionsActivity java file so that the first scene is presented when the activity is created This can be achieved as follows package com ebookfrenzy scenetransitions import android support v7 app AppCompatActivity import android os Bundle import android transition Scene import android transition Transition import android transition TransitionManager import android view ViewGroup import android view View public class SceneTransitionsActivity extends AppCompatActivity ViewGroup rootContainer Scene scene1 Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity scene transitions rootContainer ViewGroup findViewById R id rootContainer scene1 Scene getSceneForLayout rootContainer R layout scene1 layout this scene1 enter The code added to the activity class declares some variables in which to store references to the root container and first scene and obtains a reference to the root container view The getSceneForLayout method of the Scene class is then used to create a scene from the layout contained in the scene1 layout xml file to convert that layout into a scene The scene is then entered via the

    Original URL path: http://www.techotopia.com/index.php/Implementing_Android_6_Scene_Transitions_%E2%80%93_A_Tutorial (2016-02-13)
    Open archived version from archive

  • Working with the Floating Action Button and Snackbar - Techotopia
    of a CoordinatorLayout manager containing entries for an app bar a toolbar and a floating action button The content fab example xml file represents the layout of the content area of the activity and contains a RelativeLayout instance and a TextView This file is embedded into the activity fab example xml file via the following include directive include layout layout content fab example The floating action button element within the activity fab example xml file reads as follows android support design widget FloatingActionButton android id id fab android layout width wrap content android layout height wrap content android layout gravity bottom end android layout margin dimen fab margin android src android drawable ic dialog email This declares that the button is to appear in the bottom right hand corner of the screen with margins represented by the fab margin identifier in the values dimens xml file which in this case is set to 16dp The XML further declares that the interior icon for the button is to take the form of the standard drawable built in email icon The blank template has also configured the floating action button to display a Snackbar instance when tapped by the user The code to implement this can be found in the onCreate method of the FabExampleActivity java file and reads as follows FloatingActionButton fab FloatingActionButton findViewById R id fab fab setOnClickListener new View OnClickListener Override public void onClick View view Snackbar make view Replace with your own action Snackbar LENGTH LONG setAction Action null show The code obtains a reference to the floating action button via the button s id and adds to it an onClickListener handler to be called when the button is tapped This method simply displays a Snackbar instance configured with a message but no actions Finally open the module level build gradle file Gradle Scripts build gradle Module App and note that the Android design support library has been added as a dependency compile com android support design 23 1 0 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters When the project is compiled and run the floating action button will appear at the bottom of the screen as shown in Figure 30 3 Figure 30 3 Tapping the floating action button will trigger the onClickListener handler method causing the Snackbar to appear at the bottom of the screen Figure 30 4 When the Snackbar appears on a narrower device as is the case in Figure 30 4 above note that the floating action button is moved up to make room for the Snackbar to appear This is handled for us automatically by the CoordinatorLayout container in the activity fab example xml layout resource file Changing the Floating Action Button Since the objective of this example is to configure the floating action button to add entries to a list the email icon currently displayed on the button needs to be changed to something more indicative of the action being performed The icon that will be used for the button is named ic add entry png and can be found in the project icons folder of the sample code download available from the following URL http www ebookfrenzy com code AndroidStudioA6Book zip Locate this image in the file system navigator for your operating system and copy the image file Right click on the app res drawable entry in the Project tool window and select Paste from the menu to add the file to the folder Figure 30 5 Next edit the activity fab example xml file and change the image source for the icon from android drawable ic dialog email to drawable ic add entry as follows android support design widget FloatingActionButton android id id fab android layout width wrap content android layout height wrap content android layout gravity bottom end android layout margin dimen fab margin android src drawable ic add entry Within the layout preview the interior icon for the button will now have changed to a plus sign The background color of the floating action button is defined by the accentColor property of the prevailing theme used by the application The color assigned to this value is declared in the colors xml file located under app res values in the Project tool window Edit this file and add a new color named colorBrightAccent xml version 1 0 encoding utf 8 resources color name colorPrimary 3F51B5 color color name colorPrimaryDark 303F9F color color name colorAccent FF4081 color color name colorBrightAccent FFFF00 color resources Next edit the styles xml file located under app res values styles and change the colorAccent entry to use the new colorBrightAccent value resources Base application theme style name AppTheme parent Theme AppCompat Light DarkActionBar Customize your theme here item name colorPrimary color colorPrimary item item name colorPrimaryDark color colorPrimaryDark item item name colorAccent color colorBrightAccent item style style name AppTheme NoActionBar item name windowActionBar false item item name windowNoTitle true item style style name AppTheme AppBarOverlay parent ThemeOverlay AppCompat Dark ActionBar style name AppTheme PopupOverlay parent ThemeOverlay AppCompat Light resources Return to the activity fab example xml and verify that the floating action button now appears with a yellow background Adding the ListView to the Content Layout The next step in this tutorial is to add the ListView instance to the content fab example xml file The ListView class provides a way to display items in a list format and can be found in the Containers section of the Designer tool palette Load the content fab example xml file into the Designer tool select Design mode if necessary and select and delete the default TextView object Locate the ListView object in the palette and drag and drop it onto the center of the layout canvas so that it appears as illustrated in Figure 30 6 Figure 30 6 With the

    Original URL path: http://www.techotopia.com/index.php/Working_with_the_Floating_Action_Button_and_Snackbar (2016-02-13)
    Open archived version from archive



  •