🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Unit_3_Design User Interface.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

SpiritedBigBen

Uploaded by SpiritedBigBen

Tainan National College of the Arts

Tags

user interface Android development software design

Full Transcript

Unit-3: Designing User Interface Designing by Declaration: User interfaces can be designed using one of two methods: procedural and declarative. Procedural simply means in code. For example, when you’re programming a Swing application, you write Java code to create and manipul...

Unit-3: Designing User Interface Designing by Declaration: User interfaces can be designed using one of two methods: procedural and declarative. Procedural simply means in code. For example, when you’re programming a Swing application, you write Java code to create and manipulate all the user interface objects such as JFrame and JButton. Thus, Swing is procedural. Declarative design, on the other hand, does not involve any code. When you’re designing a simple web page, you use HTML, a markup language similar to XML that describes what you want to see on the page, not how you want to do it. HTML is declarative. Android tries to straddle the gap between the procedural and declarative worlds by letting you create user interfaces in either style. You can stay almost entirely in Java code, or you can stay almost entirely in XML descriptors. If you look up the documentation for any Android user interface component, you’ll see both the Java APIs and the corresponding declarative XML attributes that do the same thing. It is a best practice to use declarative XML as much as possible. The XML code is often shorter and easier to understand than the corresponding Java code, and it’s less likely to change in future versions. Design UI by Graphics: Android SDK provides a set of API for drawing custom 2D and 3D graphics. When we write an app that requires graphics, we should consider how intensive the graphic usage is. In other words, there could be an app that uses quite static graphics without complex effects and there could be other app that uses intensive graphical effects like games. According to this usage, there are different techniques we can adopt: Canvas and Drawable: In this case, we can extend the existing UI widgets so that we can customize their behavior or we can create custom 2D graphics using the standard method provided by the Canvas class. Hardware acceleration: We can use hardware acceleration when drawing with the Canvas API. This is possible from Android 3.0. OpenGL: Android supports OpenGL natively using NDK. This technique is very useful when we have an app that uses intensively graphic contents (i.e games). The easiest way to use 2D graphics is extending the View class and overriding the onDraw method. We can use this technique when we do not need a graphics intensive app. In this case, we can use the Canvas class to create 2D graphics. This class provides a set of method starting with draw hat can be used to draw different shapes like: lines circle rectangle oval picture arc To draw a rectangle, we create a custom view and then we override onDraw () method. public class Design extends View { public Design(Context context) { super(context); } public Design(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public Design(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public Design(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @SuppressLint("ResourceAsColor") @Override protected void onDraw(@NonNull Canvas canvas) { super.onDraw(canvas); Paint p=new Paint(); p.setColor(Color.GREEN); p.setStrokeWidth(10); p.setStyle(Paint.Style.FILL_AND_STROKE); canvas.drawRoundRect(100,100,200,200,20,20,p); invalidate(); } } Activity_main.xml ?xml version="1.0" encoding="utf-8"?> Splash Screen in Android (creating the opening screen): A splash screen is mostly the first screen of the app when it is opened. It is a constant screen that appears for a specific amount of time and generally shows for the first time when the app is launched. Splash screen is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper. It will deliver messages and runnables to that Looper's message queue and execute them on that Looper's thread. There are two main uses for a Handler: (1) To schedule messages and runnables to be executed at some point in the future (2) To enqueue an action to be performed on a different thread than your own. Scheduling messages is accomplished with the post (Runnable), postAtTime (java.lang.Runnable, long), postDelayed(Runnable, Object, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler). When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate. Syntax of postDelayed: public final boolean postDelayed (Runnable r, long delayMillis) Where Runnable r: The Runnable that will be executed. This value cannot be null. long delayMillis: The delay (in milliseconds) until the Runnable will be executed. Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached. The time-base is SystemClock.uptimeMillis (). Time spent in deep sleep will add an additional delay to execution. Example: MainActivity.java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(MainActivity.this, MainActivity2.class); startActivity(i); finish(); } }, 2000); } activity_main.xml: activity_main2.xml: MainActivity2.java: public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main2); } } Using Alternative Resources: Android resource files are stored separately from the rest of java files of application. Generally resources are stored as xml files. Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more. Alternative resources are provided for specific device configurations by grouping them in specially named resource directories. At runtime, Android uses the appropriate resource based on the current configuration. For example, you might want to provide a different UI layout depending on the screen size or different strings depending on the language setting. Graphics and raw data can be stored as resources. Resources can be categorized according to screen characteristics, language and region, input methods, device configurations, etc. All resources must be stored in the /res directory of project. So directory hierarchy is strictly maintained. Each resource type corresponds to a particular sub-directory. All the graphics files are stored under /res/drawable folder of directory. It is a good practice to keep non code resources external to our code. Android supports externalization of resources and it can range from simple values such as strings, colors to complex things like images, etc. By storing these resources externally we ease their management, maintenance and updates. Android is intelligent enough to select correct resources without interruption of user explicitly. Thus customization becomes much easier.By storing these resources externally we ease their management, maintenance and updates. Android is intelligent enough to select correct resources without interruption of user explicitly. Thus customization becomes much easier. ADT plug-in automatically detects any new resource file added to the project. These resources are compiled. This generates the R.java file which enables us to access resources programmatically. Android provides different type of application resources: Animation resources: Define pre-determined animations. Tween animations are saved in res/anim/ and accessed from the R.anim class. Frame animations are saved in res/drawable/ and accessed from the R.drawable class. Color state list resource: Define a color resource that changes based on the View state. Saved in res/color/ and accessed from the R.color class. Drawable resources: Define various graphics with bitmaps or XML. Saved in res/drawable/ and accessed from the R.drawable class. Layout resource: Define the layout for your application UI. Saved in res/layout/ and accessed from the R.layout class. Menu resource: Define the contents of your application menus. Saved in res/menu/ and accessed from the R.menu class. String resources: Define strings, string arrays, and plurals and include string formatting and styling. Saved in res/values/ and accessed from the R.string, R.array, and R.plurals classes. Style resource Define the look and format for UI elements. Saved in res/values/ and accessed from the R.style class. Font resources Define font families and include custom fonts in XML. Saved in res/font/ and accessed from the R.font class. Provide alternative resources: Most apps provide alternative resources to support specific device configurations. For instance, include alternative drawable resources for different screen densities and alternative string resources for different languages. At runtime, Android detects the current device configuration and loads the appropriate resources for your app. To specify configuration-specific alternatives for a set of resources, do the following: Create a new directory in res/ named in the form -.  is the directory name of the corresponding default resources (defined in table 1).  is a name that specifies an individual configuration for which these resources are to be used. You can append more than one. Separate each one with a dash. Save the appropriate alternative resources in this new directory. The resource files must be named exactly the same as the default resource files. Example: Create a Folder anim under res folder and create resource file tween.xml MainActivity.java public class MainActivity extends AppCompatActivity { ImageView i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); i=(ImageView)findViewById(R.id.img); Animation animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.tween); i.startAnimation(animation); } } Implementing an about Box(Dialogs): When the user selects the About button, meaning that either they touch it (if they have a touch screen) or they navigate to it with the D-pad (directional pad) or trackball and press the selection button, we want to pop up a window with some information about Application. After scrolling through the text, the user can press the Back button to dismiss the window. We can accomplish this in several ways:  Define a new Activity, and start it.  Use the AlertDialog class, and show it.  Subclass Android’s Dialog class, and show that. For this example, let’s define a new activity.The About activity will need a layout file. We will name it res/layout/ about.xml: Now add strings for the title of the About dialog box and the text it contains to res/values/strings.xml: About Please Accept the terms and condition by clicking ok button The About activity should be defined in About.java. All it needs to do is override onCreate( ) and call setContentView( ). public class About extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); } } To start an activity in Android, we first need to create an instance of the Intent class. There are two kinds of intents: public (named) intents that are registered with the system and can be called from any application and private (anonymous) intents that are used within a single application. A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog doesn't fill the screen and is normally used for modal events that require users to take an action before they can proceed. The Dialog class is the base class for dialogs, but don't instantiate Dialog directly. Instead, use one of the following subclasses: AlertDialog:A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog:A dialog with a predefined UI that lets the user select a date or time. AlertDialog: An AlertDialog is a specific type of Dialog that is used to display a message or prompt the user for input. It can have a title, message, and one or more buttons for the user to interact with. It can also be customized by using custom layouts or themes. layout.Android AlertDialog is composed of three regions: title, content area and action buttons.  Title - In Android Alerts, you can display a title with up to 3 buttons, a custom layout, a list of selectable items, or a message based on the need. And the title is optional. If you want to present a simple message or question, then the title is not required.  Content Area - This displays a message. It can be a list or custom layouts depending on the necessities.  Action Button - This displays action buttons for user interaction. There should not be more than three action buttons in AlertDialog, and they are positive, negative, and neutral. Positive is used to accept and continue with the action. Negative to cancel the action. Neutral is used when the user wants to proceed with the action but unnecessarily intends to cancel. Methods of AlertDialog class: Method Type Description setIcon(Int) This method is used to set the icon of the AlertDialog. setMessage(CharSequence) This method is used to display the message. setTitle(CharSequence) This method set the title to appear in the Dialog box This method sets the property such that the dialog can be setCancelable(boolean) canceled or not setOnCancelListener(DialogInterface. This method Sets the callback such that it will be called if the OnCancelListener onCancelListener) dialog is canceled. setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, This method sets a list of items to be displayed in the dialog DialogInterface.OnMultiChoiceClickL as the content. The listener will notify the selected option. istener listener) The AlertDialog class takes care of automatically setting WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM for you based on whether any views in the dialog return true from View.onCheckIsTextEditor(). Generally you want this set for a Dialog without text editors, so that it will be placed on top of the current input method UI. You can modify this behavior by forcing the flag to your desired mode after calling onCreate(Bundle). Builder(Context context):Creates a builder for an alert dialog that uses the default alert dialog theme. Some of the methods of AlertDialog.Buider are: public AlertDialog.Builder setPositiveButton (int textId, DialogInterface.OnClickListener listener): Set a listener to be invoked when the positive button of the dialog is pressed. public AlertDialog.Builder setNegativeButton (CharSequence text, DialogInterface.OnClic kListener listener):Set a listener to be invoked when the negative button of the dialog is pressed. public AlertDialog.Builder setTitle (CharSequence title):Set the title displayed in the Dialog. public AlertDialog.Builder setView (View view):Set a custom view to be the contents of the Dialog. If the supplied view is an instance of a ListView the light background will be used. public AlertDialog show ():Creates a AlertDialog with the arguments supplied to this builder and show()'s the dialog. MainActivity.java: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); AlertDialog.Builder alertdialog=new AlertDialog.Builder(this); alertdialog.setTitle("About"); alertdialog.setView( getLayoutInflater().inflate(R.layout.custom_layout,null)); alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"Thanks for Accepting",Toast.LENGTH_LONG).show(); } }); alertdialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog a=alertdialog.create(); a.show(); } } activity_main.xml: Custom_layout.xml: Applying a theme: A theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy—not just an individual view. When you apply a theme, every view in the app or activity applies each of the theme's attributes that it supports. Themes can also apply styles to non-view elements, such as the status bar and window background. A theme defines a collection of named resources that can be referenced by styles, layouts, widgets, and so on. Themes assign semantic names, like color Primary, to Android resources. There are four different methods to Change or Add Themes to Android Studio. Changing default theme Add the theme to Android Studio by importing jar file Adding theme from Android Studio plugin section Adding theme by copying ICLS file to a particular directory Method 1: Changing default theme First of all, open your Android Studio: In Android Studio, there are three default themes available i.e. Intellij Light, Dracula, and High Contrast. To change default themes go to File and click on Settings. Under the Appearance & Behaviour -> Appearance, you will find Theme. Choose the right theme from the drop-down and click on Apply and then Ok. Here you can see the background and color scheme for all three themes. Intellij Light theme Dracula theme High Contrast theme Method 2: Add the theme to Android Studio by importing jar file Download the jar file. To import this theme to our Android Studio, go to the File > Manage IDE Settings > Import Settings, a new dialog box will be open. Now select the downloaded jar file or you can do drag and drop too then click on Ok.After clicking Ok, a new dialog box will open where we can select what component we want to import from jar file to editor. Here select both colors and schemes and then click Ok. After this, a new box will be open. Click on the Restart button to reload the settings. Here you can see the new theme. You can follow the same steps while importing any jar files. Method 3: Adding theme from Android Studio plugin section There is another way to add themes to the android studio by downloading the themes from the plugin section. Go to the File > Settings > Plugins. Click on Marketplace and search for themes. Ex. Themes. Here you can see a lot of different themes and select one and download it, after downloading you can apply these themes to your IDE and these downloaded themes will be available in your default themes collection. Method 4: Adding theme by copying ICLS file to a particular directory %USERPROFILE%/.AndroidStudio/config/colors Once you have copied the ICLS file to the above directory then restart the Android Studio so that theme will be applied to the IDE. We apply a theme with the android:theme attribute on either the tag or an tag in the AndroidManifest.xml file. Adding a menu: Menus are useful for displaying additional options that are not directly visible on the main UI of an application. There are two main types of menus in Android: The CreateMenu() method takes a Menu argument and adds a series of menu items to it.To add a menu item to the menu, you create an instance of the MenuItem class and use the add() method of the Menu object. The four arguments of the add() method are as follows:  groupId:The group identifier that the menu item should be part of. Use 0 if an item is not in a group.  itemId :Unique item ID  order:The order in which the item should be displayed  title:The text to display for the menu item You can use the setAlphabeticShortcut() method to assign a shortcut key to the menu item so that users can select an item by pressing a key on the keyboard. The setIcon() method sets an image to be displayed on the menu item. The MenuChoice() method takes a MenuItem argument and checks its ID to determine the menu item that is clicked. It then displays a Toast message to let the user know which menu item was clicked. Options menu: Displays information related to the current activity. In Android, you activate the options menu by pressing the MENU key. To display the options menu for your activity, you need to override two methods in your activity: onCreateOptionsMenu() and onOptionsItemSelected(). The onCreateOptionsMenu() method is called when the MENU button is pressed. In this event, you call the CreateMenu() helper method to display the options menu. When a menu item is selected, the onOptionsItemSelected() method is called. Context menu: Displays information related to a particular view on an activity. In Android, to activate a context menu you tap and hold on to it. A context menu is usually associated with a view on an activity, and it is displayed when the user long clicks an item. For example, if the user taps on a Button view and hold it for a few seconds, a context menu can be displayed. If you want to associate a context menu with a view on an activity, you need to call the setOnCreateContextMenuListener() method of that particular view. activity_main.xml: options_menu.xml: MainActivity.java package com.example.menu; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show(); if (id == R.id.search_item) { // do your code return true; } else if (id == R.id.upload_item){ // do your code return true; } else if (id == R.id.copy_item){ // do your code return true; } else if (id == R.id.print_item){ // do your code return true; } else if (id == R.id.share_item){ // do your code return true; } else if (id == R.id.bookmark_item){ // do your code return true; } else{ return super.onOptionsItemSelected(item); } } } context menu example: activity_main.xml: MainActivity.java package com.example.menu; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); Button btn = (Button) findViewById(R.id.btnShow); registerForContextMenu(btn); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Context Menu"); menu.add(0, v.getId(), 0, "Upload"); menu.add(0, v.getId(), 0, "Search"); menu.add(0, v.getId(), 0, "Share"); menu.add(0, v.getId(), 0, "Bookmark"); } @Override public boolean onContextItemSelected(MenuItem item) { Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } } Adding Settings: Android provides a nice facility for defining what all your program preferences are and how to display them using almost no code. In many apps, we have seen the Settings screen which is most common in most of the apps. This settings screen is used to manage the preferences of the users. For creating this settings screen android provides a feature to make a settings preferences screen. You define the preferences in a resource file called res/xml/settings.xml: xmlns:android="http://schemas.android.com/apk/res/android" > Debugging: The same techniques you use to debug programs on other platforms can be applied to Android. These include printing messages to the log and stepping through your program in a debugger. Debugging with Log Messages: The Log class provides several static methods to print messages of various severity levels to the Android system log: Log.e( ): Errors Log.w( ): Warnings Log.i( ): Information Log.d( ): Debugging Log.v( ): Verbose Log.wtf( ): What a Terrible Failure Debugging output in the LogCat view Debugging is uses Android log will be during development. Debugging with the Debugger In addition to log messages, you can use the debugger to set breakpoints, single step, and view the state of your program. First, enable your project for debugging by adding the android: debuggable="true" option in your AndroidManifest.xml file.

Use Quizgecko on...
Browser
Browser