Android From Scratch: Understanding Views And View Groups
2022-9-19 22:57:0 Author: code.tutsplus.com(查看原文) 阅读量:16 收藏

Do you find it easier to learn with video? Why not check out our course:

1. Views

View objects are used specifically for drawing content onto the screen of an Android device. While you can instantiate a View in your Java code, the easiest way to use them is through an XML layout file. An example of this can be seen when you create an simple "Hello World" application in Android Studio. The layout file is the one named activity_main.xml, looking something like this.

<TextView
    android:id="@+id/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

The above example shows a type of View that will be displayed on the screen. The layout_width and layout_height attributes state that View should only take up as much room on the screen as needed to display the text "Hello World!". The id attribute is how that View can be referenced in your Java code like this:

setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.hello_world);

While you can set attributes for a View in XML, you can also change attributes in your Java code, such as changing the text of the above TextView.

textView.setText("This is a changed View");

The above code updates the text of the TextView to "This is a changed View". This is what that looks like when you run the app.

Now that you know how to work with basic View objects, let's go over some of the different types that are available to you in the Android SDK.

Display Views

TextView

This is the View we used in the above example. The main job of the TextView is to display text on the screen of an Android app. While this may seem like a simple task, the TextView class contains complex logic that allows it to display marked up text, hyperlinks, phone numbers, emails, and other useful functionality.

Here are some important attributes that you can set for a TextView in XML:

  • android:layout_width  — This will set the width of the TextView element. It can either be a constant dynamic like match_parent or wrap_content or it can be a fixed value like 20dp or 40sp etc.
  • android:layout_height — This will set the height of the TextView element. It can also either be a constant dynamic value or something fixed such as 15dp or 20.5sp etc.
  • android:text — You can use this attribute to set the text to whatever you want to display on the screen.
  • android:textColor — Use this attribute to specify a color value either as a reference to another image or as a hex color value.
  • android:gravity — Control the alignment of the text when it takes less space than the TextView. You can set it as top, bottom, left, right, center etc.

The TextView class gives you access to a lot of methods to get and set the values of different properties. We have already seen how to use setText() to specify a text value for the view. You can similarly specify values for other attributes such as the textColor and gravity using the methods setTextColor() and setGravity()

TextClock is another useful class that extends TextView to display the current date and/or time to users as a formatted string. You can use also use the following attributes with this class to show time in a specific format or from a specific time zone.

  • android:format12Hour — This attribute is useful for specifying the format to show date/time in the 12 hour mode.
  • androidformat24Hour — This attribute is useful for specifying the format to show date/time in the 24 hour mode.
  • android:timeZone — This attribute is useful for specifying the time zone to use.

ImageView

The ImageView class extends the View class. As the name implies, the ImageView is designed specifically to display images on the screen. This can be used for displaying resources stored in the app or for displaying images that are downloaded from the internet.

Input and Controls

Some View objects are used for more than just displaying content to users. Sometimes you need to receive some sort of input to control your applications. Luckily, Android provides several View subclasses specifically for this purpose.

Button

The Button class extends from the TextView class. It is one of the most basic controls available in an app. It listens for clicks from the user and calls a method in your code so that you can respond appropriately. Since, Button extends the TextView class we can use the methods and attributes from TextView to control the appearance and behavior of Button. Here is an example:

<Button
     android:id="@+id/button_id"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Click Me"
     android:onClick="takeAction" />

The above button will execute the takeAction() method upon each click. Keep in mind that you will have to implement a method with this name inside the layout's activity class.

Switch and CheckBox

The Switch and CheckBox classes have an active and inactive state that can be toggled between. This is useful for changing settings in an app.

EditText

This View subclass is an extension of the TextView class and allows users to update the contained text via keyboard input. The EditText class inherits a lot of attributes from the TextView class so you can use android:layout_width, android:layout_height, android:gravity etc. to control the position and alignment of the view as well as its content. You can also control the width of the input with android:ems attribute.

The EditText class is used to create a user interface element for people to enter and modify text. This text input can be of different types like the date, number, numberPassword, textPassword, text, textPersonName etc. All these are valid values for the android:inputType attribute. The value you specify for the attribute will determine the type of keyboard shown to users.

<EditText                                   
    android:id="@+id/lock_pin"              
    android:layout_width="wrap_content"     
    android:layout_height="wrap_content"    
    android:ems="10"                        
    android:inputType="numberPassword" />

The following image shows how the keyboard adapts to setting the inputType to numberPassword or text.

Different keyboard types in EditTextDifferent keyboard types in EditTextDifferent keyboard types in EditText

Adapter-Based Views

The AdapterView class is an extension of the ViewGroup class. While each of the above View examples are single items, sometimes you want to display a collection of items. These View classes require the use of an Adapter to handle displaying the proper user interface per item in a collection. The Adapter does a couple of important things like providing access to the data items that you want to display and creating a View for each item in the data set.

Some common classes that are direct or indirect subclasses of AdapterView are listed below.

ListView

The ListView class is used for displaying a collection of items in a linear, single-column, scrollable View. Each individual item can be selected for displaying more details or performing an action related to that item. Keep in mind that a ListView does not contain any information about the type and content of views that it contains.

The ListView class has been around for a while now. There is now an alternate RecyclerView class that you should consider using instead of ListView. RecyclerView is more flexible and provides better performance in comparison.

GridView

Similar to the ListView class, the GridView class takes an Adapter and displays items in multiple columns on the screen. The GridView class basically provides a two-dimensional scrolling grid.

The GridView is suitable for creating layouts where you want to create a scrollable container with items displayed in form of a grid. However, GridView is now obsolete just like ListView. You should consider using RecyclerView in its place.

Spinner

The final collection View class for you to learn about in this tutorial is the Spinner class. It accepts an Adapter and displays items in a dropdown menu when the Spinner is clicked so that an item can be selected by the user.

2. View Groups

A ViewGroup is an invisible object used to contain other View and ViewGroup objects in order to organize and control the layout of a screen. ViewGroup objects are used for creating a hierarchy of View objects (see below) so that you can create more complex layouts. That said, the more simple you can keep a layout, the more performant it is.

ViewGroup objects can be instantiated in the same way as standard View items in XML or in Java code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <TextView
        android:id="@+id/hello_world_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 2!" />
</LinearLayout>

While all ViewGroup classes perform a similar task, each ViewGroup subclass exists for a specific purpose. Let's take a look at some of them.

LinearLayout

The LinearLayout exists to display items in a stacked order, either horizontally or vertically. Linear layouts can also be used to assign weights to child View items so that the items are spaced on the screen in a ratio to each other.

RelativeLayout

This ViewGroup subclass allows you to display items on the screen relative to each other, providing more flexibility and freedom over how your layout appears compared to the LinearLayout.

FrameLayout

Designed for displaying a single child View at a time, the FrameLayout draws items in a stack and provides a simple way to display an item across various screen sizes.

ScrollView

It is an extension of the FrameLayout class. The ScrollView class handles the scrolling of its child object on the screen. You can also add multiple views within the scroll view. Just make sure that the direct child is a view group and other views are placed within that child.

It is used for managing multiple views while only displaying one at a time, the ViewPager class accepts an Adapter and allows users to swipe left and right in order to see all available View items.

RecyclerView

The RecyclerView class is a ViewGroup subclass that is an improvement over the now obsolete ListView and GridView classes and that has been made available by Google through the AndroidX support library for older versions of Android.

The RecyclerView class requires the use of the view holder design pattern for efficient item recycling and it supports the use of a LayoutManager, a decorator, and an item animator in order to make this component incredibly flexible at the cost of simplicity.

In simple terms, the RecyclerView class provides a modern and more performant solution for your layout needs. It can be used with an appropriate LayoutManager in order to create both one-dimensional list and two-dimensional grid layouts.

The LayoutManager is responsible for a bunch of things such as the positioning of item views and determining when it should recycle item views that are no longer in user's view.

CoordinatorLayout

The CoordinatorLayout class uses a Behavior object to determine how child View items should be laid out and moved as the user interacts with your app. It will basically allow you to coordinate different views so that the animations and transitions among them become seamless and easy to implement.

3. Custom Views

While there is a wide variety of View and ViewGroup classes for you to use within your apps, you sometimes want to create something new to fit your needs. In this case, you can create a new Java class that extends either View or ViewGroup, depending on what you need. The act of creating a new custom View subclass is beyond the scope of this article, but you can find more information in this Envato Tuts+ tutorial about creating custom views.

Conclusion

In this tutorial, you have learned about one of the most basic components of Android, layouts and views. Given how fundamental these components are to Android, you will continuously learn new things about them as you continue to work with the Android platform and you will find new ways to do amazing things using them in your projects.

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.


文章来源: https://code.tutsplus.com/tutorials/android-from-scratch-understanding-views-and-view-groups--cms-26043
如有侵权请联系:admin#unsafe.sh