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".
  • An Introduction to Using Fragments in Android Studio - Techotopia
    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 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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

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


  • Using Fragments in Android Studio - An Example - Techotopia
    the fragment layout as follows 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 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 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 id text fragment eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 Using Fragments in Android Studio 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 app Activity 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 Before moving on we

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

  • An Android Studio Master/Detail Flow Tutorial - Techotopia
    file used on small screen devices By default this contains a FrameLayout instance to which will be added user interface elements declared by the kind name FragmentDetail class kind name DetailFragment java The Java class that accompanies the fragment kind name detail xml XML resource file The code in this method loads the data associated with the master list and displays the content of the fragment kind name detail xml file to the user fragment kind name detail xml The kind name detail user interface for the detail pane that is displayed within the onCreateView method of the kind name DetailFragment class By default this contains a single TextView object instance and is used in both two pane and small screen modes DummyContent java A class file intended to provide sample data for the template This class can either be modified to meet application needs or replaced entirely By default the content provided by this class simply consists of a number of string items Two additional files are also of interest purely for the sake of understanding how the application is able to identify whether to use two pane mode or not These files are res values large refs xml and res values sw600dp refs xml As will be outlined in greater detail in the chapter entitled Handling Different Android Devices and Displays each application project has multiple sets of resources that target different display sizes At runtime the Android system automatically uses the resource set that most closely matches the physical display size of the device The values large and values sw600dp resources are of course used in devices with larger displays The ref xml files in these folders simply declare an alias that causes the two pane mode layouts to be used item name activity item list type layout layout activity item twopane item Modifying the Master Detail Flow Template Whilst the structure of the Master Detail Flow template can appear confusing at first the concepts will become clearer as the default template is modified in the remainder of this chapter As will become evident much of the functionality provided by the template can remain unchanged for many master detail implementation requirements In the rest of this chapter the MasterDetailFlow project will be modified such that the master list displays a list of web site names and the detail pane altered to contain a WebView object instead of the current TextView When a web site is selected by the user the corresponding web page will subsequently load and display in the detail pane Changing the Content Model The content for the example as it currently stands is defined by the DummyContent class file Begin therefore by selecting the DummyContent java file located in the Project tool window in the app java com ebookfrenzy masterdetailflow dummy folder and reviewing the code At the bottom of the file is a declaration for a class named DummyItem which is currently able to store two String objects representing a content string and

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

  • Creating and Managing Overflow Menus in Android Studio - Techotopia
    makes menu item selections All that an activity needs to do to receive menu selection notifications is to override the onOptionsItemSelected method Passed as an argument to this method is a reference to the selected menu item The getItemId method may then be called on the item to obtain the ID which may in turn be used to identify which item was selected For example Override public boolean onOptionsItemSelected MenuItem item switch item getItemId case R id menu red Red item was selected return true case R id menu green Green item was selected return true default return super onOptionsItemSelected item Creating Checkable Item Groups In addition to configuring independent menu items it is also possible to create groups of menu items This is of particular use when creating checkable menu items whereby only one out of a number of choices can be selected at any one time Menu items can be assigned to a group by wrapping them in the group tag The group is declared as checkable using the android checkableBehavior property setting the value to either single all or none The following XML declares that two menu items make up a group wherein only one item may be selected at any given time menu xmlns android http schemas android com apk res android group android checkableBehavior single item android id id menu red android orderInCategory 1 app showAsAction never android title string red string item android id id menu green android orderInCategory 2 app showAsAction never android title string green string group menu When a menu group is configured to be checkable a small circle appears next to the item in the menu as illustrated in Figure 27 4 It is important to be aware that the setting and unsetting of this indicator does not take place automatically It is therefore the responsibility of the application to check and uncheck the menu item Figure 27 4 Continuing the color example used previously in this chapter this would be implemented as follows Override public boolean onOptionsItemSelected MenuItem item switch item getItemId case R id menu red if item isChecked item setChecked false else item setChecked true mainLayout setBackgroundColor android graphics Color RED return true case R id menu green if item isChecked item setChecked false else item setChecked true mainLayout setBackgroundColor android graphics Color GREEN return true default return super onOptionsItemSelected item Creating the Example Project To see the overflow menu in action create a new project in Android Studio entering MenuExample 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 a blank activity named MenuExampleActivity with corresponding layout and menu resource files named activity menu example and menu menu example When the project has been created navigate to the app res layout folder

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

  • Animating User Interfaces in Android Studio using the Transitions Framework - Techotopia
    displayed To display a scene to the user without any transition animation the enter method is called on the scene instance scene1 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 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 Whilst 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 button2 targets changeBounds fade android duration 2000 android fadingMode fade in transitionSet eBookFrenzy com Purchase the fully updated Android 6

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

  • An Android Studio Transition Tutorial using beginDelayedTransition - Techotopia
    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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android view MotionEvent import android view View import android view ViewGroup import android widget RelativeLayout public class TransitionDemoActivity extends ActionBarActivity 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 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 29 1 Figure 29 1 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android view MotionEvent import android view View import android view ViewGroup import android widget RelativeLayout import android transition TransitionManager public class TransitionDemoActivity extends ActionBarActivity public void handleTouch View view findViewById

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

  • Implementing Android Scene Transitions – An Android Studio Tutorial - Techotopia
    version of the first scene The first and second buttons will still be present but will be located in the bottom right and left hand corners of the layout respectively The third button on the other hand 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 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 30 3 Figure 30 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 ActionBarActivity import android os Bundle import android view Menu import android view MenuItem import android transition Scene import android transition Transition import android transition TransitionManager import android view ViewGroup import android view View public class SceneTransitionsActivity extends ActionBarActivity 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

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

  • An Overview of Intents in Android Studio - Techotopia
    correctly configured for an application containing activities named ActivityA and ActivityB xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy intent1 intent1 application android icon drawable ic launcher android label string app name activity android label string app name android name com ebookfrenzy intent1 intent1 ActivityA intent filter action android name android intent action MAIN category android name android intent category LAUNCHER intent filter activity activity android name ActivityB android label ActivityB activity application manifest Returning Data from an Activity As the example in the previous section stands whilst data is transferred to ActivityB there is no way for data to be returned to the first activity which we will call ActivityA This can however be achieved by launching ActivityB as a sub activity of ActivityA An activity is started as a sub activity by starting the intent with a call to the startActivityForResult method instead of using startActivity In addition to the intent object this method is also passed a request code value which can be used to identify the return data when the sub activity returns For example startActivityForResult i REQUEST CODE In order to return data to the parent activity the sub activity must implement the finish method the purpose of which is to create a new intent object containing the data to be returned and then calling the setResult method of the enclosing activity passing through a result code and the intent containing the return data The result code is typically RESULT OK or RESULT CANCELED but may also be a custom value subject to the requirements of the developer In the event that a sub activity crashes the parent activity will receive a RESULT CANCELED result code The following code for example illustrates the code for a typical sub activity finish method public void finish Intent data new Intent data putExtra returnString1 Message to parent activity setResult RESULT OK data super finish In order to obtain and extract the returned data the parent activity must implement the onActivityResult method for example protected void onActivityResult int requestCode int resultCode Intent data String returnString if resultCode RESULT OK requestCode REQUEST CODE if data hasExtra returnString1 returnString data getExtras getString returnString1 Note that the above method checks the returned request code value to make sure that it matches that passed through to the startActivityForResult method When starting multiple sub activities it is especially important to use the request code to track which activity is currently returning results since all will call the same onActivityResult method on exit eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 Implicit Intents Unlike explicit intents which reference the Java class name of the activity to be launched implicit intents identify the activity to be launched by specifying the

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



  •