import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Toast; public class List_Fragment extends ListFragment implements OnItemClickListener { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.list_fragment, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1); setListAdapter(adapter); getListView().setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) { Toast.makeText(getActivity(), \"Item: \" + position, Toast.LENGTH_SHORT).show(); } } Following code will be the content of MainActivity.java package com.example1.ts7.myapplication; 51 CU IDOL SELF LEARNING MATERIAL (SLM)
import android.support.v7.app.AppCompatActivity; 52 import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } following code will be the content of manifest.xml, which has placed at res/AndroidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example1.ts7.myapplication\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> CU IDOL SELF LEARNING MATERIAL (SLM)
Running the Application Let's try to run the SimpleListFragment application we just created. I assume you had created your AVD while doing the environment set-up. To run the app from Android Studio, open one of your project's activity files and click the Run icon from the toolbar. Android installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display the following Emulator window – Figure 3.3. List Fragment output Fragments transaction – Transition has two main responsibilities − 1. Capture the state of each view in both the start and end scenes. 2. Create an Animator based on the differences that will animate the views from one scene to the other. Example Create your custom animation with fragment transition .So let's follow the following steps − Step 1 you will use android studio to create android software and name it as fragmentcustomanimations under a package com.Example1.Fragmentcustomanimations, with the blank pastime. 53 CU IDOL SELF LEARNING MATERIAL (SLM)
Step 2 Regulate the activity_main.Xml, which has positioned at res/layout/activity_main.Xml to add a textual content view Three create a layout called fragment_stack.Xml.Xml underneath the directory res/layout to outline your fragment tag and button tag Four create a folder, which is placed at res/ and name it as animation and upload fragment_slide_right_enter.Xml fragment_slide_left_exit.Xml, fragment_slide_right_exit.Xml, and fragment_slide_left_enter.Xml Five in MainActivity.Java, need to feature fragment stack, fragment manager, and oncreateview () 6 run the application to release the android emulator and verify the end result of the modifications carried out in the application. The following could be the content of res.Format/activity_main.Xml it contained textview <?xml version=\"1.0\" encoding=\"utf-8\"?> <TextViewxmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/text\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_vertical|center_horizontal\" android:text=\"@string/hello_world\" android:textAppearance=\"?android:attr/textAppearanceMedium\" /> Following will be the content of res/animation/fragment_stack.xml file. it contained frame layout and button <?xml version=\"1.0\" encoding=\"utf-8\"?> 54 <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" > CU IDOL SELF LEARNING MATERIAL (SLM)
<fragment android:id=\"@+id/fragment1\" android:name=\"com.exam.listfragmentdemo.List_Fragment \" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout> Following will be the content of the res/animation/fragment_left_enter.xml file. it contained a set method and object animator <?xml version=\"1.0\" encoding=\"utf-8\"?> <set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"100dp\" android:valueTo=\"0dp\" android:valueType=\"floatType\" android:propertyName=\"translationX\" android:duration=\"@android:integer/config_mediumAnimTime\" /> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"0.0\" android:valueTo=\"1.0\" android:valueType=\"floatType\" android:propertyName=\"alpha\" android:duration=\"@android:integer/config_mediumAnimTime\" /> </set> following will be the content of res/animation/fragment_slide_left_exit.xml file.it contained set and object animator tags. <?xml version=\"1.0\" encoding=\"utf-8\"?> 55 CU IDOL SELF LEARNING MATERIAL (SLM)
<set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"0dp\" android:valueTo=\"-100dp\" android:valueType=\"floatType\" android:propertyName=\"translationX\" android:duration=\"@android:integer/config_mediumAnimTime\" /> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"1.0\" android:valueTo=\"0.0\" android:valueType=\"floatType\" android:propertyName=\"alpha\" android:duration=\"@android:integer/config_mediumAnimTime\" /> </set> Following code will be the content of res/animation/fragment_slide_right_enter.xmlfile.it contained set and object animator tags <?xml version=\"1.0\" encoding=\"utf-8\"?> <set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"-100dp\" android:valueTo=\"0dp\" android:valueType=\"floatType\" android:propertyName=\"translationX\" android:duration=\"@android:integer/config_mediumAnimTime\" /> <objectAnimator 56 android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"0.0\" android:valueTo=\"1.0\" CU IDOL SELF LEARNING MATERIAL (SLM)
android:valueType=\"floatType\" android:propertyName=\"alpha\" android:duration=\"@android:integer/config_mediumAnimTime\" /> </set> following code will be the content of res/animation/fragment_slide_right_exit.xmlfile, it contained set and object animator tags <?xml version=\"1.0\" encoding=\"utf-8\"?> <set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"0dp\" android:valueTo=\"100dp\" android:valueType=\"floatType\" android:propertyName=\"translationX\" android:duration=\"@android:integer/config_mediumAnimTime\" /> <objectAnimator android:interpolator=\"@android:interpolator/decelerate_quint\" android:valueFrom=\"1.0\" android:valueTo=\"0.0\" android:valueType=\"floatType\" android:propertyName=\"alpha\" android:duration=\"@android:integer/config_mediumAnimTime\" /> </set> following code will be the content of src/main/java/MainActivity.java file. it contained button listener, stack fragment and onCreateView package com.example1.fragmentcustomanimations; import android.app.Activity; 57 import android.app.Fragment; CU IDOL SELF LEARNING MATERIAL (SLM)
import android.app.FragmentTransaction; 58 import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class Fragment_CustomAnimations extends Activity { int mStackLevel = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_stack); // Watch for button clicks. Button button = (Button)findViewById(R.id.new_fragment); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { addFragmentToStack(); } }); if (savedInstanceState == null) { // Do first time initialization -- add initial fragment. Fragment newFragment = Counting_Fragment.newInstance(mStackLevel); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.simple_fragment, newFragment).commit(); } else CU IDOL SELF LEARNING MATERIAL (SLM)
{ 59 mStackLevel = savedInstanceState.getInt(\"level\"); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(\"level\", mStackLevel); } void addFragmentToStack() { mStackLevel++; // Instantiate a new fragment. Fragment newFragment = Counting_Fragment.newInstance(mStackLevel); // Add the fragment to the activity, pushing this transaction // on to the back stack. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.setCustomAnimations(R.animator.fragment_slide_left_enter, R.animator.fragment_slide_left_exit, R.animator.fragment_slide_right_enter, R.animator.fragment_slide_right_exit); ft.replace(R.id.simple_fragment, newFragment); ft.addToBackStack(null); ft.commit(); } public static class CountingFragment extends Fragment { int mNum; /** * Create a new instance of CountingFragment, providing \"num\" * as an argument. CU IDOL SELF LEARNING MATERIAL (SLM)
*/ 60 static CountingFragmentnewInstance(int num) { CountingFragment f = new CountingFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt(\"num\", num); f.setArguments(args); return f; } /** * When creating, retrieve this instance's number from its arguments. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments() != null ? getArguments().getInt(\"num\") : 1; } /** * The Fragment's UI is just a simple text view showing its * instance number. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroupcontainer,BundlesavedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText(\"Fragment #\" + mNum); CU IDOL SELF LEARNING MATERIAL (SLM)
tv.setBackgroundDrawable(getResources(). 61 getDrawable(android.R.drawable.gallery_thumb)); return v; } } } the following will be the content of AndroidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example1.fragment_customanimations\" android:versionCode=\"1\" android:versionName=\"1.0\" > <application android:allowBackup=\"true\" android:icon=\"@drawable/ic_launcher\" android:label=\"@string/app_name\" android:theme=\"@style/AppTheme\" > <activity android:name=\"com.example1.fragment_customanimations.MainActivity\" android:label=\"@string/app_name\" > <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> Running the Application CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 3.4. custom animation with fragment1 Let's try to run our Fragment Transitions application we just created. I assume you had created your AVD while doing the environment set-up. To run the app from Android Studio, open one of your project's activity files and click the Run Eclipse Run Icon from the toolbar. Android installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display the following Emulator window: Android fragment transit If click on the new fragment, it going to be changed the first fragment to the second fragment as Figure 3.5. Custom animation with fragment2 62 CU IDOL SELF LEARNING MATERIAL (SLM)
3.3FRAGMENT LIFE CYCLE Fragment’s Lifecycle Each fragment example comes with its personal lifecycle. While the consumer navigates and interacts with the android utility, fragment transitions through more than one tiers inside the lifecycle are brought, deleted, and exit or enter the display, therefore. For coping with the lifecycle, fragment implements the ‘lifecycleowner’ alongside exposing the lifecycle items which can without difficulty be accessed via the method getlifecycle(). Every feasible lifecycle nation is also represented inside the lifecycle. Its foremost components are: 1. Initialised 2. Created 3. Started 4. Resumed 5. Destroyed By developing the fragment on the pinnacle of the lifecycle, the android developer can use the classes and techniques available for handling the lifecycles with the lifecycle-conscious components. For instance, with the assist of lifecycle-conscious components, you may easily show the tool vicinity at the display. This aspect routinely starts off evolved processing when the fragment receives lively. It stops listening whilst the fragment moves to an inactive country. As an alternative for the use of the lifecycle observer, fragment magnificence incorporates callback methods corresponding to every one of the changes in the fragment lifecycle. This is such as techniques like onCreate (), onStart(), onPause(), onResume(), onStop(), and so forth. The fragment also has a separate lifecycle this is independently controlled from the lifecycle fragment. The lifecycle fragments also keep lifecycle for their view, Gaining access to the lifecycle of the view is beneficial for conditions in which lifecycle conscious and other components can carry out the tasks, and the fragmented view exists. A number of those instances consist of looking at stay records this is simplest supposed for showing the statistics at the display screen. This segment discusses the fragment lifecycle together with explaining the policies that decide the lifecycle kingdom and the relationship among the fragment lifecycle callbacks and lifecycle states. Fragments and the fragments manager Whilst any fragment is instantiated inside the system, it starts the initialized country. For any fragment to remain in transition through the rest of the lifecycle, it's far essential to be added to the ‘fragment manager. The fragment supervisor is totally liable for determining the kingdom of the fragment that has to be shifting them into the same kingdom. Beyond the fragment lifecycle, the fragment supervisor is chargeable for including the fragments in their host hobby and educating them every time the fragment is not suitable for use. The fragment 63 CU IDOL SELF LEARNING MATERIAL (SLM)
elegance additionally has callback strategies, which are onDetach(), and onAttach(). You can additionally override these techniques to perform the paintings when either of these strategies can arise. The on Attach () callback simplest works whilst the fragment has been added within the fragment manager, and then it is attached to the host activity. In this instance, the fragment is lively, and the fragment manager is handling the lifecycle state. At this factor, the fragment manager technique returns this fragment. The onAttach() method is referred to as previous to the lifecycle nation adjustments. The onDetach() callback is only involved while the fragment has been deleted from the fragment supervisor, and it's far detached from the host pastime. The fragment is likewise now not active, and it cannot be retrieved with the assist of findfragmentbyid(). The onDetach() approach is also known as after the lifecycle country trade. Be aware: these callbacks are commonly unrelated to the fragment transaction strategies detach () and fix(). Fragment lifecycle states and callbacks While figuring out the fragment lifecycle nation, the fragment manager undertakes the subsequent movements: The maximum set of a fraction is decided by the fragment supervisor. In addition, the fragment cannot progress past the kingdom of the fragment supervisor. The fragment lifecycle nation can never be larger than its figure. As an instance, a parent hobby or fragment can simplest be started earlier than its corresponding toddler fragments. Likewise, the kid fragments have to be stopped prior to their parent activity or fragment. Observe: you can keep away from using the <fragment> tag to add the fragment with the assist of XML because the <fragment> tag permits the fragment to transport past the nation of fragment supervisor for including the fragment via XML. 64 CU IDOL SELF LEARNING MATERIAL (SLM)
Image Source: https://developer.android.com/guide/fragments/lifecycle Figure 3.6. States Of Fragment’s Lifecycle And Its Relation With Callbacks The above discern highlights lifecycle states of the fragment and homes lifecycle states related to the fragment lifecycle callbacks and consider lifecycle. Because the fragment progresses at some point of the lifecycle, it moves downward or upward through the lifecycle states. As an instance, a fragment that receives introduced to the top of the stack moves upward following the stairs: created, started, and resumed. As the fragment lifecycle is popped off the returned stack, it movements down through the states going from resumed to start out, and finally to destroy. Upward straight transitions When moving upward thru the lifecycle states, a fraction first calls any of the associated lifecycles and callbacks for the same new kingdom. Once this lifecycle kingdom callback is finished, the detailed lifecycle event is emitted to the user with the aid of the lifecycle fragment. It's far followed with the aid of the lifecycle fragment view if it's far instantiated. ● fragment created 65 CU IDOL SELF LEARNING MATERIAL (SLM)
While the fragment reaches the created nation, it gets brought to the fragment manager, and the approach onattach() is already referred to as upon. You need to remember the fact that the view of the fragment has now not been advanced presently, and any of the software states related to the fragmented view can simplest be restored if it has been created first . This fragment transition additionally invokes the oncreate () callback. This callback receives savedinstancestate package argument having any country this is previously saved by means of the onsaveinstancestate(). You have to know that the savedinstancestate basically has the value null whilst the fragment is created for the primary time. But it additionally has a non- null cost for next recreations even supposing the person does not override onsaveinstancestate(). ● fragment created and think about initialized The fragment to your lifecycle is the handiest created while the fragment offers a valid view instance. In most cases, you could use any of the fragment constructors to take a layout. This can routinely inflate the fragmented view at a particular time. You could additionally overwrite the lifecycle oncreateview() to programmatically inflate or develop your fragment view. If your fragment view is already instantiated with a non-null price, then the view is best set at the fragment, and it may be retrieved using the getview() approach. The getviewlifecycleownerlivedata () is now up to date with the newly initialized lifecycleowner similar to the fragmented view. The onviewcreated () lifecycle callback is eventually referred to as at this degree. That is the actual place to installation the initial country of the fragmented view and to begin gazing the instances and to set up the adaptors on any view page or recycler view times within the fragmented view. ● fragment and consider created As soon as the fragmented view is created, the preceding fragment view state is restored, and the lifecycle view is moved into the created nation. The view lifecycle proprietor can emit the on_create occasion to see. To this degree, you could effortlessly repair the nation associated with the fragmented view. The translation of this kingdom invokes the callbackonviewstaterestored(). ● fragment and consider commenced It's miles fantastically endorsed to companion the lifecycle-aware additives to the began additives of a fraction of this State and also show the fragmented view to remain. If everybody factor is created, then it is dependable to carry out the fragments transaction on the kid fragment manager of the equal fragment. If anyways, the fragment view value holds non- null, then the lifecycle view of the fragment is moved to start out right after the fragment lifecycle, after which it moved. Whilst the fragment also will become started out, the onstart() callback is in addition worried. 66 CU IDOL SELF LEARNING MATERIAL (SLM)
● fragment and think about resumed Whilst the application fragment is seen, all the transition and animator effects had been finished, and the fragment is ready for user interplay. The lifecycle of the fragment also movements to the state of resumed, and onresume () callback is invoked. The transition to this country is ideal for indicating that the person is able to interact with the application fragment. The software fragments that are not resumed at this nation can be manually set to recognition at the view or try to input the enter approach visibility. Down load country transitions When the fragment moves downward to any low lifecycle nation, the applicable lifecycle occasion is likewise emitted to the see via the lifecycle fragment view. If this occasion is instantiated following the lifecycle of the fragment, then the fragment calls the associated lifecycle callback. ● fragment and examine started out As long as the user begins to leave the fragment, then it's far nonetheless visible. If the lifecycle of the fragment is seen, then its view is moved again to the state started, and it emits on_pausee event to the watch. This fragment invokes onPause() call returned as well. ● fragment and examine created If the fragment is no longer seen, then the lifecycle of the declaration and its views are moved into the state created, and it emits the on_stop occasion. This state transition isn't always best precipitated with the parent fragment or activity forestall however additionally with the aid of the saving of country through any parent fragment . This conduct additionally ensures that the onstop event is worried prior to the fragments kingdom saved. 3.4 SUMMARY • We understood fragments and many other elements. With the exception of listening to the audio, the integration of user interaction with Android systems is visual in nature. Most of these interactions usually take place through the user interface of the Android application that is installed on a device. This is inclusive of the built-in applications and third-party applications installed by the Android user. Therefore, user inputs, views, and user interface layouts, fragments, and other components act as key elements in developing Android applications that involve creating and designing user interfaces. The UI is the basic impression of any software solution from the user’s perspective. • There are various aspects related to Android user interface development that we can consider for improving application performance. These aspects act as the best measure to follow if you are willing to go deeper into the aspects of Android app development. 67 CU IDOL SELF LEARNING MATERIAL (SLM)
3.5 KEYWORDS • Fragment-Fragments are like parts of activity • AndroidManifest.xml-It contains informations about activities, content providers, permissions etc. • Android Virtual Device (AVD)-It is used to test the android application without the need for mobile or tablet etc. • Stopped State- When an activity is not visible, but still in memory, we say it’s in Stopped State • Intents- Intents are messages that are sent among major building blocks. 3.6 LEARNING ACTIVITY 1. Create an application to demonstrate the call-back methods of a Fragment lifecycle by displaying the toast messages on the changing of states. ___________________________________________________________________________ __________________________________________________________________________ 2. Create an application that shows a fragment with the click of a button. The fragment must have a list of fruit names. ___________________________________________________________________________ ______________________________________________________ 3. Write an application to display two different fragments with the click of two different buttons. The first fragment is having a Text View to display a message and the second fragment is having a toggle button. The toggle button shows a toast message on the state changing. ___________________________________________________________________________ _____________________________________________________________ 3.7UNIT END QUESTIONS A. Descriptive Questions 68 Short Questions 1. How to call context in Fragment. 2. Explain the parameters of onCreateView(). 3. How many ways to call Fragment. 4. What is FragmentManagerClass?. 5. Is Fragment Life Cycle dependent on Activity Life Cycle? CU IDOL SELF LEARNING MATERIAL (SLM)
Long Questions 1. What are Fragments in Android? 2. Fragment Life Cycle in Android? 3. States Of Fragment’s Lifecycle And Its Relation With Callbacks 4. How does the communication between two fragments occur? 5. When should you use a fragment instead of an Android activity? B. Multiple Choice Questions 1. Which one is NOT related to fragment class? a. DialogFragment b. ListFragment c. PreferenceFragment d. CursorFragment 2. Definition of Loader? a. loaders make it easy to asynchronously load data in an activity or fragment. b. loaders make it easy to synchronously load data in an activity or fragment. c. loaders does not make it easy to asynchronously load data in an activity or fragment. d. None of these 3. Characteristics of the Loaders? a. They are available to every Activity and Fragment. b. They provide asynchronous loading of data. c. They monitor the source of their data and deliver new results when the content changes. d. They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data. e. All of these 4. How many ways to start services? 69 a. Started CU IDOL SELF LEARNING MATERIAL (SLM)
b. Bound c. a & b d. None of these 5. If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the ________class? a. Messenger b. Binder c. AIDL d. None of these Answers 1-d, 2-a, 3-e, 4-c, 5-b 3.8 REFERENCES Reference Books • Khoshafian, et al. (1990). Object orientation: Concepts, Languages, Databases. New York: John Wiley & Sons • Thornsby, J. (May 2016). Android UI Design. Packt Publishing. Morris, J. (Feb 2011). Android User Interface Development - Beginner’s Guide. UK. Packt Publishing Websites • https://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-UI-Design.pdf • https://www.techotopia.com/index.php/Understanding_Android_Views,_View_Group s_and_Layouts • https://www.tutorialspoint.com/software_architecture_design/user_interface.htm • https://www.wideskills.com/android/building-user-interface/listening-to-ui- notifications-in-android • https://developer.android.com/guide/fragments/lifecycle 70 CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 4: UI-WIDGETS Structure 4.0 Learning Objectives 4.1 Introduction 4.2 Buttons 4.3 Toast 4.4 Custom Toast 4.5 Toggle Button 4.6 Switch Button 4.7 Image Button 4.8 Check Box 4.9 Spinner 4.10 Summary 4.11 Keywords 4.12 Learning Activity 4.13 Unit End Questions 4.14 References 4.0LEARNING OBJECTIVES After studying this unit, you will be able to: • Explain UI-Widgets working • Explain working with Buttons, • Implement use of Toast, Custom Toast, • Use and benefit of Toggle Button, Switch Button, Image Button, • Implement Check Box and • Explain working with Spinner 4.1 INTRODUCTION Widgets will show our application's new and exciting content in a consolidated form. Customers can effortlessly flow, if supported, resize widgets across domestic panels Records widgets 71 CU IDOL SELF LEARNING MATERIAL (SLM)
Information widgets display a few elements of importance to a user and tune how those facts adjustments over the years, which include climate or pastime rankings. Tapping the widget will launch the associated app into the display screen. Collection widgets Series widgets will show multiple elements having an equal type, they recognition on two interactions: Browsing a collection Starting a detail’s detail screen Manage widgets Control widgets show often used functions. Those features will cause the home display without commencing the application. For instance, the tuning app allows playing, pause, or bypass tune tracks from outside. Hybrid widgets Many widgets integrate factors of the different types. Centre your widget on the sort of sorts and add elements of others as required. App widgets Miniature utility perspectives that can be embedded in different applications Conduct Scrolling Listing or grid-based totally series widgets normally amplify or agree on the vertical scrolling area. No matter the widget's size, the consumer can still scroll all factors... Scrollable widgets List or grid-based series widgets amplify the vertical scrolling area. The person can still scroll all elements into view. For smaller widget sizes, give attention to the importance and then upload more contextual statistics. Non-scrollable widgets Statistics widgets aren't scrollable. All content and layout have to dynamically fit into the dimensions selected via the user. 72 CU IDOL SELF LEARNING MATERIAL (SLM)
Resizing Resizing lets users modify the peak or width of a widget. This lets in users to influence the format of widgets on domestic panels. Your... Resizing allows users to regulate the peak or width of a widget. This allows users to influence the format of widgets on home panels. An extended press and subsequent launch set resizable widgets into resize mode. Customers can use the drag handles or the widget corners to set the desired size. Responsive resizing Widgets must accommodate specific spacing necessities across devices, together with a cellular number, length, and spacing versions. Navigation Your widgets must offer navigation hyperlinks to frequently used regions of your app, which include: Your widgets ought to offer navigation links to often used areas of your app, including: Configuring Once positioned on a domestic screen panel, android widgets display their configuration alternatives. Configuration must: as soon as set up, widgets do not usually display a \"setup\" or... As soon as positioned on a domestic display screen panel, android widgets show their configuration picks. 4.2 BUTTONS A Button class represents a push-button widget in Android. The full package path for the button class in android. widgets. Button. Buttons are clicked to perform an action. A button can display text or an icon, or both. Event handlers for Button click events are defined with the android:onClick attribute of the <Button> element or programmatically by setting the setOnClickListener(View.OnClickListener). Button In the first example we define a button that closes an activity when pressed. 73 CU IDOL SELF LEARNING MATERIAL (SLM)
AndroidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.zetcode.finish\" android:versionCode=\"1\" android:versionName=\"1.0\"> <application android:label=\"@string/app_name\" android:icon=\"@drawable/ic_launcher\"> <activity android:name=\"MainActivity\" android:label=\"@string/app_name\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> This is the manifest file for the program. main.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" > <Button android:layout_height=\"wrap_content\" android:layout_width=\"wrap_content\" android:layout_marginTop=\"10dip\" android:text=\"@string/btnlabel\" android:onClick=\"onClick\" /> </LinearLayout> In the main.xml layout file, we define one button widget with the <Button> element. The first two attributes define the size of the button so that it is big enough to show its content. The android:layout_marginTop=\"10dip\" creates a margin between the title bar of the screen and the button widget. The dip (density-independent pixel) is a unit of measurement that is used for Android layout management. It best reflects the rich diversity of resolutions and densities of various Android appliances. The android:text=\"@string/bin label\" attribute defines a text for the button. The actual text resides in the strings.xml file, which we cover before long. Finally, the android:onClick=\"onClick\" attribute creates a button event listener for the click event. All we need to do is to define the onClick() method in the relevant Java source file. 74 CU IDOL SELF LEARNING MATERIAL (SLM)
strings.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <resources> <string name=\"app_name\">Finish button</string> <string name=\"btnlabel\">Finish</string> </resources> In the strings.xml file, we have two resource strings. The first is used in the manifest file to provide a name for the application and the main activity. The second is used in the layout file to provide a text label for the button widget. MainActivity.java import android.app.Activity; import android.view.View; import android.os.Bundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClick(View view) { finish(); } } This is the source file for the main activity. We have defined an onClick() method which reacts to the button click events. It must take a View as its sole parameter. The method calls the finish() method which closes the current activity. We are redirected back to the list of applications. Figure 4.1.: Button 75 CU IDOL SELF LEARNING MATERIAL (SLM)
Clicking on the button we are redirected back to the list of applications. 4.3 TOAST Showing a toast A toast is a view that contains a short message for the user. Toasts may be displayed for a short or a protracted time frame. In our 2nd utility, we create a button widget. It's going to show a toast message after being pressed. Androidmanifest.Xml <?Xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.Android.Com/apk/res/android\" package=\"com.Zi.Toast\" Android:versionCode=\"1\" Android:versionName=\"1.0\"> <application android:label=\"@string/app_name\" Android:icon=\"@drawable/ic_launcher\"> <activity android:name=\"MainActivity\" Android:label=\"@string/app_name\"> <intent-filter> <action android:name=\"android.Intent.Action.MAIN\" /> <category android:name=\"android.Intent.Category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> That is the occur file. Important.Xml <?Xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns:android=\"http://schemas.Android.Com/apk/res/android\" Android:orientation=\"vertical\" Android:layout_width=\"fill_parent\" Android:layout_height=\"fill_parent\" > <Button Android:id=\"@+id/btnId\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginTop=\"10dip\" Android:text=\"@string/label\" /> 76 CU IDOL SELF LEARNING MATERIAL (SLM)
</LinearLayout> In the foremost.Xml format document, we've one button widget in the linearlayout, which arranges widgets in a single row or column. The button has an android:identification=\"@+identification/btn_id\" attribute. The characteristic substances an identifier name for the button. We are able to retrieve the button inside the main interest using the findviewbyid() method. Widgets that are not being referenced do not want this attribute. The plus sign is used whilst we create the id of the element. Next references to the element inside the XML record could be used without the plus signal. (as an instance in layout managers.) Strings.Xml <?Xml version=\"1.0\" encoding=\"utf-8\"?> <resources> <string name=\"app_name\">display toast</string> <string name=\"label\">show</string> </resources> This is the strings.Xml aid document. The button will have the 'show' text label. MainActivity.Java Import android.App.Activity; Import android.Os.Package; Import android.View.View; Import android.View.View.Onclicklistener; Import android.View.Gravity; Import android.Widget.Button; Import android.Widget.Toast; Import android.Content.Context; Public class MainActivity extends interest @override public void onCreate(package deal savedinstancestate) Exquisite.Oncreate(savedinstancestate); Setcontentview(r.Format.Principal); Initui(); public void initial() 77 CU IDOL SELF LEARNING MATERIAL (SLM)
button btn = (button) findviewbyid(r.Identity.Btnid); Btn.Setonclicklistener(new onclicklistener() @override public void onClick(view arg0) context ctx = getapplicationcontext(); string msg = \"button turned into clicked\"; int length = toast.Length_short; toast toast = toast.Maketext(ctx, msg, period); Toast.Setgravity(gravity.Center, 0, zero); Toast.Show(); ); When we click on the button widget, it will display a toast message within the middle of the display screen. The toast will be displayed for a short time period. ... Import android.View.View.Onclicklistener; Import android.View.Gravity; Import android.Widget.Button; Import android.Widget.Toast; Import android.Content material.Context; Those are some of the new instructions needed to be imported in this example. Initui(); Inside the onCreate() technique we name the initial() technique. It adds the onClickListener() to the button widget. Button btn = (button) findviewbyid(r.Identity.Btn_id); We get the connection with the button widget that we have certain within the main.Xml record. We use the findviewbyid() method. The technique unearths a view (a button is a kind of a view) by using the id attribute from the main.Xml file. The id is placed inside the vehicle-generated r magnificence. Btn.Setonclicklistener(new onclicklistener() @override 78 public void onClick(view arg0) CU IDOL SELF LEARNING MATERIAL (SLM)
. ); Context ctx = getapplicationcontext(); String msg = \"button changed into clicked\"; Int length = toast.Length_short; Toast toast = toast.Maketext(ctx, msg, period); Toast.Setgravity(gravity.Center, 0, zero); Toast.Show(); We set up and show the toast view. We get the utility context, create a message, and the length of time. Gravity is the alignment of the view inside its discern. We role the toast in the center of the display. By means of default, the toasts are displayed at the bottom of the screen. 4.4 CUSTOM TOAST In android, sometimes easy toast might not be pleasant, and then we will move to customize a toast. For creating a custom format, define a view layout, in XML and pass the foundation view object to the setView(view) approach. Steps for implementation of custom toast in android: Step 1: first off retrieve the layout inflater with getLayoutInflater() (or getSystemService()) after which inflate the layout from XML the use of inflate(int, viewGroup). In inflate, method first parameter is the layout resource identity and the second is the basic view. Step 2: create a new toast with toast(context) and set some residences of the toast, which include the length and gravity. Step three: name setView(view) and skip the inflated format on this approach. Step 4: display the toast on the display screen the usage of the display() method of toast. Within the beneath example, we've got shown the functioning of toast and custom toast. Android custom toast example Create a new android utility with the use of android studio and supply names as a toast example. open activity_main.Xml 79 CU IDOL SELF LEARNING MATERIAL (SLM)
Activity_main.Xml <?Xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns:android=\"http://schemas.Android.Com/apk/res/android\" Android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\" Android:orientation=\"vertical\" > <Button Android:id=\"@+id/btnShow\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:text=\"Show Custom Toast\" Android:layout_marginTop=\"150dp\" android:layout_marginLeft=\"110dp\"/> </LinearLayout> If you look at the above code we created a one-button manipulate within the XML format report to reveal the custom toast notification when we click on the button. Now we want to create a custom format for our toast notification, that creates a brand new XML report (custom_toast.Xml) in /layout folder, and write the code as proven beneath. Custom_toast.Xml 80 <?Xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns:android=\"http://schemas.Android.Com/apk/res/android\" Android:id=\"@+id/custom_toast_layout\" Android:orientation=\"horizontal\" Android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\" Android:paddingLeft=\"10dp\" Android:paddingRight=\"10dp\" Android:background=\"#80CC28\"> <ImageViewandroid:src=\"@drawable/ic_notification\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginRight=\"10dp\" /> CU IDOL SELF LEARNING MATERIAL (SLM)
<TextViewandroid:id=\"@+id/txtvw\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginTop=\"13dp\" Android:textColor=\"#FFF\" Android:textStyle=\"bold\" Android:textSize=\"15dp\" /> </LinearLayout> In case you take a look at the above code we're loading a photo (ic_notification) from a drawable folder so that you want to feature your icon in a drawable folder to reveal it inside the notification. Once we're executed with the advent of layout with required controls, we need to load the XML layout aid from our interest onCreate() callback technique, for that open main pastime file MainActivity.Java and write the code like as proven under. MainActivity.Java Package com.Tt.Customtoastexample; Import android.Os.Bundle; Import android.View.Gravity; Import android.View.Layoutinflater; Import android.View.View; Import android.View.Viewgroup; Import android.Widget.Button; Import android.Widget.Textview; Import android.Widget.Toast; Public class MainActivity extends appcompatactivity 81 @override covered void oncreate(package deal savedinstancestate) CU IDOL SELF LEARNING MATERIAL (SLM)
Splendid.Oncreate(savedinstancestate); Setcontentview(r.Layout.Activity_main); button btn = (button)findviewbyid(r.Identity.Btnshow); Btn.Setonclicklistener(new view.Onclicklistener() @override public void onclick(view v) Layoutinflater inflater = getlayoutinflater(); view layout = inflater.Inflate(r.Format.Custom_toast, (viewgroup) findviewbyid(r.Identity.Custom_toast_layout)); Textview television = (textview) layout.Findviewbyid(r.Identification.Txtvw); Television.Settext(\"custom toast notification\"); toast toast = new toast(getapplicationcontext()); Toast.Setgravity(gravity.Center_vertical, 0, a hundred); Toast.Setduration(toast.Length_long); Toast.Setview(layout); Toast.Display(); ); In case you take a look at the above code we are calling our custom toast notification through the usage of the layout inflater item and displaying a toast notification on the button click on. Generally, during the release of our interest, the onCreate() callback technique will be known as by means of the android framework to get the desired format for an interest. The output of android custom toast example While we run the above example 82 CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 4.3. Android Custom Toast Notification Example Result 4.5 TOGGLE BUTTON A toggle button lets in converting among the 2 states. Toggle button object is used for the basic toggle button for layout. If we need to alternate a button's state ourselves, we can use the compoundButton.Setchecked() or compoundButton.Toggle() method. To realize when the person activates the button or switch, We create a compoundButton.OnCheckedChangelistener object and assign it to the button by way of calling setoncheckedchangelistener(). As an instance: Togglebutton toggle = (togglebutton) findviewbyid(r.Id.Togglebutton); Toggle.Setoncheckedchangelistener(new compoundbutton.Oncheckedchangelistener() public void oncheckedchanged(compoundbuttonbuttonview, booleanischecked) 83 CU IDOL SELF LEARNING MATERIAL (SLM)
if (ischecked) // the toggle is enabled else // the toggle is disabled ); 4.6 SWITCH BUTTON The android switch button is a UI widget that has only states i.E. On and off. It allows the user to exchange the setting between these two states. Figure 4.4. Toggle Button 84 The android transfer button is available in android 4.0 or later gadgets. Example: You may use these buttons to exchange the on and off state of WiFi or Bluetooth Step 1: Creating a project Create an android application named “switch_button_example”. Step 2: developing layout Exchange res ->format -> activity_main.Xml as beneath: <?Xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayoutxmlns:android=\"http://schemas.Android.Com/apk/res/android\" Xmlns:tools=\"http://schemas.Android.Com/tools\" Android:id=\"@+id/activity_main\" Android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\" Android:paddingBottom=\"@dimen/activity_vertical_margin\" Android:paddingLeft=\"@dimen/activity_horizontal_margin\" Android:paddingRight=\"@dimen/activity_horizontal_margin\" Android:paddingTop=\"@dimen/activity_vertical_margin\" Android:gravity=\"center_horizontal\" Tools:context=\"com.Java2blog.Switch_button_example.MainActivity\"> CU IDOL SELF LEARNING MATERIAL (SLM)
<Switch 85 Android:id=\"@+id/switch1\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:text=\"Switch : \" > </Switch> </RelativeLayout> Step 3: Creating mainactivity Change src/major/packagename/mainactivity.Java as under: Bundle com.Java2g.Switchbuttonexampleapp; Import android.App.Interest; Import android.Aid.V7.App.Appcompatactivity; Import android.Os.Package; Import android.View.View; Import android.Widget.Transfer; Import android.Widget.Toast; Import android.View.View.Onclicklistener; Public magnificence mainactivity extends appcompatactivity switch switchbutton; personal activity interest; @override protected void oncreate(bundle savedinstancestate) Extremely good.Oncreate(savedinstancestate); Setcontentview(r.Layout.Activity_main); activity = this; Switchbutton = (switch) findviewbyid(r.Identity.Switch1); Switchbutton.Setonclicklistener(new onclicklistener() @override public void onclick(view v) if (switchbutton.Ischecked()) Toast.Maketext(hobby, \"transfer is in on nation\", toast.Length_long).Show(); else CU IDOL SELF LEARNING MATERIAL (SLM)
Toast.Maketext(activity, \"transfer is in off nation\", toast.Length_long).Display(); ); We are becoming transfer references from the layout report and then the usage of transfer setonclicklistener to sign up an event for a country exchange. Switch’s isChecked() approach is used to recognize the contemporary country of switch whether or not it's far on level or off kingdom. Step 4: walking the app Whilst you run the app, you will get the underneath display screen: Figure 4.5. Switch Button Example When you click on switch button, it will go to one state. 86 CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 4.6. Switch Button On State Example When you again click on switch button, it will go to off state. Figure 4.7. Switch Button off Example 4.7 IMAGE BUTTON Image button is an interface control this is used to display a button with an image and to perform a motion while a consumer clicks or faucets on it. 87 CU IDOL SELF LEARNING MATERIAL (SLM)
By way of default, the image button seems similar to the regular button and it performs a motion when a consumer clicks or touches it, however, the simplest distinction is we can add a custom Image to the button. Example of usage of photo buttons in android applications. Android buttons with example In android, we have extraordinary sorts of buttons available to use based totally on our necessities, those are the button, image button, toggle button, and radio button. In android, we are able to add a photo to the button through the use of <ImageButton> characteristic android: src within the XML format report or by using using the setimageresource() Method. In android, we are able to create image button manage in two ways either within the XML format report or create it in the activity report programmatically. Create imagebutton in xml layout file Following is the pattern way to define image button control inside the XML layout file within the android software. <?Xml version=\"1.0\" encoding=\"utf-8\"?> < LinearLayoutxmlns: android=\"http://schemas.Android.Com/apk/res/android\" Android:orientation=\"vertical\" android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\"> <ImageButton Android:id=\"@+id/addBtn\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:src=\"@drawable/add_icon\" /> </LinearLayout> If you observe the above code snippet, here we defined imagebutton manage and we are showing the image from the drawable folder the use of the android: src characteristic within the XML format report. Create Imagebutton control In android, we can create imagebutton manage programmatically in an activity file. 88 CU IDOL SELF LEARNING MATERIAL (SLM)
Example for imagebutton control dynamically in an activity. Linearlayout layout = (linearlayout)findviewbyid(r.Identity.L_layout); Imagebuttonbtn = new imagebutton(this); Btn.Setimageresource(r.Drawable.Add_icon); Format.Addview(btn); Normally, whenever the consumer clicks on imagebutton object will receive an on-click on occasion. In android, we can define the button click on the event in methods either inside the XML format document or create it in the Activity file programmatically. Outline imagebutton click on the event in the XML layout document We are able to add the event handler for the button using android:onclick to the <ImageButton> element in our XML layout document. The cost of android:onClick characteristic must be the call of the technique which we want to name in reaction to a click event and the interest record which hosting XML format ought to enforce the corresponding method. defining a button click on the event android:onclick attribute in xml layout file. <?Xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns: android=\"http://schemas.Android.Com/apk/res/android\" Android:orientation=\"vertical\" android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\"> <ImageButton Android:id=\"@+id/addBtn\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:src=\"@drawable/add_icon\" Android:onClick=\"addOperation\"/> </LinearLayout> In pastime that hosts our XML layout report, we need to put into effect click on occasion approach like as shown beneath /** known as when the consumer touches the button */ 89 Public void addoperation(view view) CU IDOL SELF LEARNING MATERIAL (SLM)
// do something in response to button click Define imagebutton click on the event in Activity record In android, we can define imagebutton click occasion programmatically in activity record instead of XML layout report. create view.Onclicklistener object and assign it to the button through calling setonclicklistener(view.Onclicklistener) like as shown underneath. Imagebuttonbtnadd = (imagebutton)findviewbyid(r.Id.Addbtn); Btnadd.Setonclicklistener(new view.Onclicklistener() Public void onclick(view v) // do something in response to button click ); That is how we will take care of imagebutton click activities in android packages. Android imagebutton manage instance Example of defining one imagebutton and two edittext controls in linearlayout to get the statistics of edittext controls when clicking on imagebutton within the application. Create a brand new android application with the use of android studio and give names as button_example. open an activity_main.Xml file 90 Activity_main.Xml <?Xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayoutxmlns: android=\"http://schemas.Android.Com/apk/res/android\" Android:orientation=\"vertical\" android:layout_width=\"match_parent\" Android:layout_height=\"match_parent\" android:id=\"@+id/l_layout\"> <TextView Android:id=\"@+id/fstTxt\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginLeft=\"100dp\" CU IDOL SELF LEARNING MATERIAL (SLM)
Android:layout_marginTop=\"150dp\" Android:text=\"First Number\"/> <EditText Android:id=\"@+id/firstNum\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginLeft=\"100dp\" Android:ems=\"10\"/> <TextView Android:id=\"@+id/secTxt\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:text=\"Second Number\" Android:layout_marginLeft=\"100dp\" /> <EditText Android:id=\"@+id/secondNum\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginLeft=\"100dp\" Android:ems=\"10\" /> <ImageButton Android:id=\"@+id/addBtn\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:layout_marginLeft=\"100dp\" Android:src=\"@drawable/add_icon\" /> </LinearLayout> If you observe the above code we created one imagebutton, two textview controls, and two edittext controls in the XML format report. 91 CU IDOL SELF LEARNING MATERIAL (SLM)
As soon as we're achieved with the creation of layout with required manipulate, we want to load the XML format useful resource from our activity oncreate() callback technique, for that open essential activity record mainactivity.Java And write the code like as shown underneath. Mainactivity.Java Import android.Os.Package; Import android.View.View; Import android.Widget.Edittext; Import android.Widget.Imagebutton; Import android.Widget.Toast; Public mainactivity extends appcompatactivity { @override protected void oncreate(package savedinstancestate) Notable.Oncreate(savedinstancestate); Setcontentview(r.Layout.Activity_main); very last edittextfirstnum = (edittext)findviewbyid(r.Identification.Firstnum); very last edittextsecnum = (edittext)findviewbyid(r.Identification.Secondnum); Imagebuttonbtnadd = (imagebutton)findviewbyid(r.Id.Addbtn); Btnadd.Setonclicklistener(new view.Onclicklistener() @override public void onclick(view v) secnum.Gettext().Tostring().Isempty()) Toast.Maketext(getapplicationcontext(), \"please fill all of the fields\", toast.Length_short).Display(); else 92 int num1 = integer.Parseint(firstnum.Gettext().Tostring()); int num2 = integer.Parseint(secnum.Gettext().Tostring()); Toast.Maketext(getapplicationcontext(), \"sum = \" + (num1 + num2), toast.Length_short).Show(); CU IDOL SELF LEARNING MATERIAL (SLM)
); } we are calling our format using the setcontentview method inside the shape of r.Layout.Layout_file_name. Usually, all through the release of our pastime, the oncreate() callback technique can be known as by way of the android framework to get the desired format for an activity. The output of the android imagebutton example Figure 4.8. Android Image Button Control Example Result Source: Tutlane.com This is how we can use ImageButton control in android applications to perform required operations on ImageButton tap or click based on our requirements. 93 CU IDOL SELF LEARNING MATERIAL (SLM)
4.8 CHECK BOX Checkboxes permit the User to pick out one or more options from a fixed. Usually, you need to gift each checkbox option in a vertical list. To create every checkbox choice, create a checkbox for your format. Due to the fact a fixed of checkbox alternatives lets in the person pick out more than one object, each checkbox is managed one by one and also you need to sign in a click on listener for everyone. A key magnificence is the following: Checkbox Responding to click on occasions When the person selects a checkbox, the checkbox object receives an on-click occasion. To define the press event handler for a checkbox, upload the android:onclick attribute to the <CheckBox> detail in your XML format. The fee for this attribute must be the call of the technique you need to call in response to a click occasion. The pastime website hosting the layout should then put into effect the corresponding technique. For example, here are a couple checkbox gadgets in a listing: <?Xml version=\"1.0\" encoding=\"utf-8\"?> 94 <LinearLayoutxmlns:android=\"http://schemas.Android.Com/apk/res/android\" Android:orientation=\"vertical\" Android:layout_width=\"fill_parent\" Android:layout_height=\"fill_parent\"> <CheckBoxandroid:id=\"@+id/checkbox_meat\" Android:layout_width=\"wrap_content\" Android:layout_height=\"wrap_content\" Android:text=\"@string/meat\" Android:onClick=\"onCheckboxClicked\"/> <CheckBoxandroid:id=\"@+id/checkbox_cheese\" Android:layout_width=\"wrap_content\" CU IDOL SELF LEARNING MATERIAL (SLM)
Android:layout_height=\"wrap_content\" Android:text=\"@string/cheese\" Android:onClick=\"onCheckboxClicked\"/> </LinearLayout> Within the activity that hosts this format, the following technique handles the press event for both checkboxes: Public void oncheckboxclicked(View view) // is the view now checked? Boolean checked = ((checkbox) view).Ischecked(); // test which checkbox became clicked transfer(view.Getid()) case r.Identification.Checkbox_meat: if (checked) // put some meat on the sandwich else // get rid of the meat ruin; case r.Identity.Checkbox_cheese: if (checked) // cheese me else // i'm lactose illiberal destroy; // todo: veggie sandwich 4.9 SPINNER Spinners provide a quick manner to pick one fee from a fixed. Inside the default state, a spinner suggests it presently decided on price. Touching the spinner presentations a dropdown menu with all other available values, from which the User can select a new one. 95 CU IDOL SELF LEARNING MATERIAL (SLM)
You can add a spinner on your format with the spinner item. You have to normally accomplish that in your xml format with a <Spinner> element. As an example: <Spinner Android:id=\"@+id/planets_spinner\" Android:layout_width=\"match_parent\" Android:layout_height=\"wrap_content\" /> To populate the spinner with a list of selections, then you definitely want to specify a spinner adapter in your activity or fragment supply code. Key Classes are subsequent: Spinner Spinneradapter Adapterview.Onitemselectedlistener Populate the spinner with personal choices The choices you provide for the spinner can come from any supply but need to be supplied thru a spinneradapter, which includes an arrayadapter if the choices are to be had in an array or a cursoradapter if the alternatives are to be had from a database question. As an instance, if the to be had selections for your spinner are pre-determined, you could offer them with a string array described in a string aid file: <?Xml version=\"1.0\" encoding=\"utf-8\"?> 96 <resources> <string-array name=\"planets_array\"> <item>mercury</item> <item>venus</item> <item>earth</item> <item>mars</item> <item>jupiter</item> CU IDOL SELF LEARNING MATERIAL (SLM)
<item>saturn</item> <item>uranus</item> <item>neptune</item> </string-array> </resources> With an array such as this one, you could use the subsequent code to your interest or fragment to supply the spinner with the array the usage of an instance of arrayadapter: Spinner spinner = (spinner) findviewbyid(r.Identification.Spinner); Arrayadapter<CharSequence> adapter = arrayadapter.Createfromresource(this, R.Array.Planets_array, android.R.Layout.Simple_spinner_item); Adapter.Setdropdownviewresource(android.R.Layout.Simple_spinner_dropdown_item); // apply the adapter to the spinner Spinner.Setadapter(adapter); The createfromresource() technique lets you create an arrayadapter from the string array. The third argument for this technique is a formatting aid that defines how the selected preference appears inside the spinner manipulate. The simple_spinner_item layout is supplied by using the platform and is the default format you must use except you want to outline your own layout for the spinner's look. You need to then call setdropdownviewresource(int) to specify the format the adapter has to use to show the list of spinner alternatives (simple_spinner_dropdown_item is some other preferred layout defined by using the platform). Name setadapter() to apply the adapter for your spinner. Responding to User selections Whilst the user selects an object from the drop-down, the spinner item receives an on-object- selected event. 97 CU IDOL SELF LEARNING MATERIAL (SLM)
To define the selection event handler for a spinner, put in force the adapterview.Onitemselectedlistener interface and the corresponding onitemselected() callback method. For example, here's an implementation of the interface in an Activity: Public magnificence spinneractivity extends pastime implements onitemselectedlistener ... Public void onitemselected(adapterview<?> determine, view view, int pos, lengthy identification) // an object was decided on. You could retrieve the chosen object the usage of // figure.Getitematposition(pos) public void onnothingselected(adapterview<?> parent) // some other interface callback The adapterview.Onitemselectedlistener calls for the onitemselected() and onnothingselected() callback methods. Then you definately want to specify the interface implementation by calling setonitemselectedlistener(): Spinner spinner = (spinner) findviewbyid(r.Id.Spinner); Spinner.Setonitemselectedlistener(this); If you implement the adapterview.Onitemselectedlistener interface along with your Activity or fragment (consisting of in the example above), you can skip this as the interface instance. 4.10 SUMMARY • We understood fragments and many different factors. Aside from taking note of the audio, the integration of user interplay with android systems is visible in nature. 98 CU IDOL SELF LEARNING MATERIAL (SLM)
Maximum of those interactions normally takes location through the User-interface of the android utility that is set up on a device. That is inclusive of the integrated programs and third-birthday party applications established with the aid of the android user. Consequently, person inputs, views, and User-interface layouts, fragments, and different additives act as key factors in developing android programs that contain creating and designing User interfaces. The UI is the primary effect of any software solution from the user’s attitude. • There are various factors related to android user interface improvement that we can remember for enhancing application performance. These aspects act because of the excellent degree to follow if you are willing to head deeper into the factors of android app development. 4.11 KEYWORDS • Control widgets- show often used functions. • Hybrid widgets- Many widgets integrate factors of the different types. • Services-Services run in the background and don’t have any user interface components. • Android Toast- Displays information for the short duration of time. • ToggleButton- It has two states ON/OFF. 4.12 LEARNING ACTIVITY 1. Write an app for calculating the multiplication of two integers. You must study integers from text fields (edittext view) and publish the solution to label (textview view) with the click of a button (button view). This all must be done in an activity. ___________________________________________________________________________ ________________________________________________________________________ 2. (trace: use the gettext() to examine a price from the edittext view and settext() technique to position the value to the textview view. Don’t forget to transform the textual content to the integer even as analysing the values from the textual content area and vice-versa when setting the values to the label.) ___________________________________________________________________________ ________________________________________________________________________ 3. Write an app to calculate the percentage of the click of different radio buttons in a radio organization. Enter the cost in the edittext view and show the solution in the textual content view. Take into account that every radio button represents a different percentage. For instance, there may be three radio buttons for 3 distinct percent consisting of 15%, 25%, and 35%. 99 CU IDOL SELF LEARNING MATERIAL (SLM)
___________________________________________________________________________ ________________________________________________________________________ 4.13 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain UI Widget. 2. Explain button. 3. Explain custom button 4. Explain spinner 5. Explain Custom toast. Long Questions 1. Give an explanation for the significance of UI widget? 2. How to use buttons, explain? 3. How toast performs an important position in software. 4. What is a custom button, how it's far extraordinary from the button. 5. Provide an explanation for the spinner with an example. B. Multiple Choice Questions 1. For creating user interface in Android, you have to use a. Eclipse b. java and XML c. java and SQL d. Java and Pl/sql 2. Android provides a few standard themes, listed in__________ a. R.style b. X.style c. menifeest.XML d. application 100 CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338